Добавление настраиваемого поля в команду FOSUserBundle не работает

0

Я искал и пытался добавить пользовательскую команду в FOSUserBundle но был невозможен :(

Я выполняю тройную проверку структуры моих файлов, CreateUserCommand находится в папке Command а UserManipulator - в папке Util.

Я также попытался перезапустить сервер и изменить команду, но не работает:

Командная строка

php app/console fos:user:create root [email protected] admin gabriel --super-admin

Ошибка:

[RuntimeException]   
  Too many arguments. 

Основной файл Bundle:

<?php

namespace INCES\ComedorBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class INCESComedorBundle extends Bundle
{
    public function getParent()
    {
        return 'FOSUserBundle';
    }
}

Мой файл CreateUserCommand:

<?php

namespace INCES\ComedorBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use FOS\UserBundle\Model\User;

/**
 * @author Matthieu Bontemps <[email protected]>
 * @author Thibault Duplessis <[email protected]>
 * @author Luis Cordova <[email protected]>
 */
class CreateUserCommand extends ContainerAwareCommand
{
    /**
     * @see Command
     */
    protected function configure()
    {
        $this
            ->setName('fos:user:create')
            ->setDescription('Create a user.')
            ->setDefinition(array(
                new InputArgument('username', InputArgument::REQUIRED, 'The username'),
                new InputArgument('email', InputArgument::REQUIRED, 'The email'),
                new InputArgument('password', InputArgument::REQUIRED, 'The password'),
                new InputArgument('nombre', InputArgument::REQUIRED, 'The nombre'),
                new InputOption('super-admin', null, InputOption::VALUE_NONE, 'Set the user as super admin'),
                new InputOption('inactive', null, InputOption::VALUE_NONE, 'Set the user as inactive'),
            ))
            ->setHelp(<<<EOT
//..
            );
    }

    /**
     * @see Command
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $username   = $input->getArgument('username');
        $email      = $input->getArgument('email');
        $password   = $input->getArgument('password');
        $nombre     = $input->getArgument('nombre');
        $inactive   = $input->getOption('inactive');
        $superadmin = $input->getOption('super-admin');

        $manipulator = $this->getContainer()->get('inces_comedor.util.user_manipulator');
        $manipulator->create($username, $password, $email, $nombre, !$inactive, $superadmin);

        $output->writeln(sprintf('Created user <comment>%s</comment>', $username));
    }

    /**
     * @see Command
     */
    protected function interact(InputInterface $input, OutputInterface $output)
    {
        // ...

        if (!$input->getArgument('nombre')) {
            $nombre = $this->getHelper('dialog')->askAndValidate(
                $output,
                'Please choose a nombre:',
                function($nombre) {
                    if (empty($nombre)) {
                        throw new \Exception('Nombre can not be empty');
                    }

                    return $nombre;
                }
            );
            $input->setArgument('nombre', $nombre);
        }
    }
}

Мой файл UserManipulator:

<?php

namespace INCES\ComedorBundle\Util;

use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Model\UserManagerInterface;

/**
 * Executes some manipulations on the users
 *
 * @author Christophe Coevoet <[email protected]>
 * @author Luis Cordova <[email protected]>
 */
class UserManipulator
{
    /**
     * User manager
     *
     * @var UserManagerInterface
     */
    private $userManager;

    public function __construct(UserManagerInterface $userManager)
    {
        $this->userManager = $userManager;
    }

    /**
     * Creates a user and returns it.
     *
     * @param string  $username
     * @param string  $password
     * @param string  $email
     * @param string  $nombre
     * @param Boolean $active
     * @param Boolean $superadmin
     *
     * @return \FOS\UserBundle\Model\UserInterface
     */
    public function create($username, $password, $email, $nombre, $active, $superadmin)
    {
        $user = $this->userManager->createUser();
        $user->setUsername($username);
        $user->setEmail($email);
        $user->setNombre($nombre);
        $user->setPlainPassword($password);
        $user->setEnabled((Boolean) $active);
        $user->setSuperAdmin((Boolean) $superadmin);
        $this->userManager->updateUser($user);

        return $user;
    }
}
  • 0
    Я не думаю, что вы можете переопределить команду. Почему бы просто не дать ему другое имя?
  • 0
    На самом деле я не хочу переопределять команду, но добавить настраиваемое поле в командной строке. Я знаю, что это можно сделать, потому что документация, проблема в том, что я не могу заставить ее работать :(. Я изменил название, чтобы прояснить проблему.
Показать ещё 2 комментария
Теги:
fosuserbundle

1 ответ

0

Вот техника, которая может помочь:

В CreateUserCommand

protected function execute(InputInterface $input, OutputInterface $output)
{
    $username   = $input->getArgument('username');
    $email      = $input->getArgument('email');
    $password   = $input->getArgument('password');
    $nombre     = $input->getArgument('nombre');
    $inactive   = $input->getOption('inactive');
    $superadmin = $input->getOption('super-admin');

    $manipulator = $this->getContainer()->get('inces_comedor.util.user_manipulator');
    $manipulator->setNombre($nombre);
    $manipulator->create($username, $password, $email, $nombre, !$inactive, $superadmin);

    $output->writeln(sprintf('Created user <comment>%s</comment>', $username));
}

и в UserManipulator добавьте:

public function setNombre($nombre)
{
    $this->nombre= $nombre;
}

и измените на:

public function create($username, $password, $email, $active, $superadmin)
  • 0
    Не работает В итоге я установил nullable поле. :(
  • 0
    Любопытно. Что именно означает «не работает»? Я использовал выше, чтобы сделать свою собственную команду создания пользователя. Разница лишь в том, что я использую PUGXMultiUserBundle, поэтому есть другой менеджер пользователей и дискриминатор класса.
Показать ещё 6 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню