70 lines
2.1 KiB
PHP
70 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace App\Command;
|
|
|
|
use Symfony\Component\Console\Command\Command;
|
|
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 Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
|
|
use Doctrine\ORM\EntityManagerInterface;
|
|
|
|
use App\Entity\User;
|
|
use App\Entity\Role;
|
|
|
|
class UserCreateCommand extends Command
|
|
{
|
|
private $encoder_factory;
|
|
private $object_manager;
|
|
|
|
public function __construct(EncoderFactoryInterface $ef, EntityManagerInterface $om)
|
|
{
|
|
$this->encoder_factory = $ef;
|
|
$this->object_manager = $om;
|
|
|
|
parent::__construct();
|
|
}
|
|
|
|
protected function configure()
|
|
{
|
|
$this->setName('user:create')
|
|
->setDescription('Create new user.')
|
|
->setHelp('Creates user and inserts into database.')
|
|
->addArgument('username', InputArgument::REQUIRED, 'username')
|
|
->addArgument('password', InputArgument::REQUIRED, 'password')
|
|
->addOption('superadmin', 'sa', InputOption::VALUE_NONE, 'Assign role of ROLE_SUPER_ADMIN.');
|
|
}
|
|
|
|
protected function execute(InputInterface $input, OutputInterface $output)
|
|
{
|
|
$username = $input->getArgument('username');
|
|
$raw_pass = $input->getArgument('password');
|
|
|
|
$user = new User();
|
|
|
|
// encode password
|
|
$enc = $this->encoder_factory->getEncoder($user);
|
|
$password = $enc->encodePassword($raw_pass, $user->getSalt());
|
|
|
|
// get entity manager
|
|
// $em = $this->getContainer()->get('doctrine')->getEntityManager();
|
|
$em = $this->object_manager;
|
|
|
|
// build user
|
|
$user->setUsername($username)
|
|
->setPassword($password)
|
|
->setEnabled();
|
|
|
|
// superadmin
|
|
if ($input->getOption('superadmin'))
|
|
{
|
|
$role = $em->getReference('App\Entity\Role', Role::SUPER_ADMIN);
|
|
$user->addRole($role);
|
|
}
|
|
|
|
$em->persist($user);
|
|
|
|
$em->flush();
|
|
}
|
|
}
|