zend-blog-3-backend
94 строки · 2.5 Кб
1<?php
2/**
3* Created by PhpStorm.
4* User: morontt
5* Date: 14.06.15
6* Time: 18:39
7*/
8
9namespace App\Command\User;
10
11use App\Service\UserManager;
12use Doctrine\ORM\EntityManagerInterface;
13use Symfony\Component\Console\Command\Command;
14use Symfony\Component\Console\Input\InputArgument;
15use Symfony\Component\Console\Input\InputInterface;
16use Symfony\Component\Console\Input\InputOption;
17use Symfony\Component\Console\Output\OutputInterface;
18use Symfony\Component\Validator\Validator\ValidatorInterface;
19
20class CreateUserCommand extends Command
21{
22/**
23* @var ValidatorInterface
24*/
25private $validator;
26
27/**
28* @var EntityManagerInterface
29*/
30private $em;
31
32/**
33* @var UserManager
34*/
35private $userManager;
36
37/**
38* @param UserManager $userManager
39* @param ValidatorInterface $validator
40* @param EntityManagerInterface $em
41*/
42public function __construct(
43UserManager $userManager,
44ValidatorInterface $validator,
45EntityManagerInterface $em
46) {
47$this->userManager = $userManager;
48$this->validator = $validator;
49$this->em = $em;
50
51parent::__construct();
52}
53
54protected function configure()
55{
56$this
57->setName('mtt:user:create')
58->setDescription('Create new user')
59->addArgument('username', InputArgument::REQUIRED, 'username')
60->addArgument('email', InputArgument::REQUIRED, 'email')
61->addOption('password', 'p', InputOption::VALUE_OPTIONAL, 'password');
62}
63
64/**
65* @param InputInterface $input
66* @param OutputInterface $output
67*
68* @return int
69*/
70protected function execute(InputInterface $input, OutputInterface $output): int
71{
72$username = $input->getArgument('username');
73$email = $input->getArgument('email');
74$password = $input->getOption('password');
75
76$user = $this->userManager->createUser($username, $email, $password);
77
78$output->writeln('');
79$errors = $this->validator->validate($user);
80if (count($errors) > 0) {
81foreach ($errors as $error) {
82$output->writeln(sprintf('<error>Error: %s</error>', $error->getMessage()));
83}
84} else {
85$this->em->persist($user);
86$this->em->flush();
87
88$output->writeln(sprintf('<info>Create user: <comment>%s</comment></info>', $username));
89}
90$output->writeln('');
91
92return 0;
93}
94}
95