Skip to content

Instantly share code, notes, and snippets.

@kevinquillen
Last active Jan 7, 2020
Embed
What would you like to do?
Example Symfony 5 maker command to create a user entity from command line.
<?php
declare(strict_types=1);
namespace App\Maker;
use Symfony\Bundle\MakerBundle\ConsoleStyle;
use Symfony\Bundle\MakerBundle\Maker\AbstractMaker;
use Symfony\Component\Console\Command\Command;
use Symfony\Bundle\MakerBundle\DependencyBuilder;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Bundle\MakerBundle\InputConfiguration;
use Symfony\Bundle\MakerBundle\Generator;
/**
* Utility command to quickly create a user entity from the command line.
*
* @package App\Maker
*/
final class AddUser extends AbstractMaker {
/**
* @var \Doctrine\ORM\EntityManagerInterface
*/
private $entityManager;
/**
* {@inheritdoc}
*/
public function __construct(EntityManagerInterface $entityManager) {
$this->entityManager = $entityManager;
}
/**
* {@inheritdoc}
*/
public static function getCommandName(): string {
return 'make:user:add';
}
/**
* {@inheritdoc}
*/
public function configureCommand(Command $command, InputConfiguration $inputConfig) {
$command
->setDescription('Creates a new user account for the application.')
->addArgument('username', InputArgument::REQUIRED, 'The account username')
->addArgument('email', InputArgument::REQUIRED, 'The email address associated with the account')
->addArgument('password', InputArgument::REQUIRED, 'The account password');
;
}
/**
* {@inheritdoc}
*/
public function configureDependencies(DependencyBuilder $dependencies)
{
$dependencies->addClassDependency(
Command::class,
'console'
);
}
/**
* {@inheritdoc}
*/
public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator) {
$user = new User();
$user->setUsername($input->getArgument('username'));
$user->setPassword($input->getArgument('password'));
$user->setEmail($input->getArgument('email'));
$this->entityManager->persist($user);
$this->entityManager->flush($user);
$this->writeSuccessMessage($io);
}
/**
* {@inheritdoc}
*/
protected function writeSuccessMessage(ConsoleStyle $io) {
$io->newLine();
$io->writeln(' <bg=green;fg=white> </>');
$io->writeln(' <bg=green;fg=white> Success! User has been created. Don\'t forget to assign roles to this user if they need elevated permission. </>');
$io->writeln(' <bg=green;fg=white> </>');
$io->newLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment