Version 1
[yaffs-website] / vendor / drupal / console / src / Command / User / CreateCommand.php
1 <?php
2 /**
3  * @file
4  * Contains \Drupal\Console\Command\User\CreateCommand.
5  */
6
7 namespace Drupal\Console\Command\User;
8
9 use Symfony\Component\Console\Input\InputInterface;
10 use Symfony\Component\Console\Input\InputArgument;
11 use Symfony\Component\Console\Input\InputOption;
12 use Symfony\Component\Console\Output\OutputInterface;
13 use Symfony\Component\Console\Command\Command;
14 use Drupal\Console\Core\Command\Shared\CommandTrait;
15 use Drupal\Core\Database\Connection;
16 use Drupal\Core\Entity\EntityTypeManagerInterface;
17 use Drupal\Core\Datetime\DateFormatterInterface;
18 use Drupal\Console\Core\Utils\ChainQueue;
19 use Drupal\Console\Utils\DrupalApi;
20 use Drupal\Console\Command\Shared\ConfirmationTrait;
21 use Drupal\user\Entity\User;
22 use Drupal\Console\Core\Style\DrupalStyle;
23
24 class CreateCommand extends Command
25 {
26     use CommandTrait;
27     use ConfirmationTrait;
28
29     /**
30      * @var Connection
31      */
32     protected $database;
33
34     /**
35      * @var EntityTypeManagerInterface
36      */
37     protected $entityTypeManager;
38
39     /**
40      * @var DateFormatterInterface
41      */
42     protected $dateFormatter;
43
44     /**
45      * @var DrupalApi
46      */
47     protected $drupalApi;
48
49     /**
50      * CreateCommand constructor.
51      *
52      * @param Connection                 $database
53      * @param EntityTypeManagerInterface $entityTypeManager
54      * @param DateFormatterInterface     $dateFormatter
55      * @param DrupalApi                  $drupalApi
56      */
57     public function __construct(
58         Connection $database,
59         EntityTypeManagerInterface $entityTypeManager,
60         DateFormatterInterface $dateFormatter,
61         DrupalApi $drupalApi
62     ) {
63         $this->database = $database;
64         $this->entityTypeManager = $entityTypeManager;
65         $this->dateFormatter = $dateFormatter;
66         $this->drupalApi = $drupalApi;
67         parent::__construct();
68     }
69
70     /**
71      * {@inheritdoc}
72      */
73     protected function configure()
74     {
75         $this
76             ->setName('user:create')
77             ->setDescription($this->trans('commands.user.create.description'))
78             ->setHelp($this->trans('commands.user.create.help'))
79             ->addArgument('username', InputArgument::OPTIONAL, $this->trans('commands.user.create.options.username'))
80             ->addArgument('password', InputArgument::OPTIONAL, $this->trans('commands.user.create.options.password'))
81             ->addOption('roles', null, InputOption::VALUE_OPTIONAL, $this->trans('commands.user.create.options.roles'))
82             ->addOption('email', null, InputOption::VALUE_OPTIONAL, $this->trans('commands.user.create.options.email'))
83             ->addOption('status', null, InputOption::VALUE_OPTIONAL, $this->trans('commands.user.create.options.status'));
84     }
85
86     /**
87      * {@inheritdoc}
88      */
89     protected function execute(InputInterface $input, OutputInterface $output)
90     {
91         $io = new DrupalStyle($input, $output);
92
93         $username = $input->getArgument('username');
94         $password = $input->getArgument('password');
95         $roles = $input->getOption('roles');
96         $email = $input->getOption('email');
97         $status = $input->getOption('status');
98
99         $user = $this->createUser($username, $password, $roles, $email, $status);
100
101         $tableHeader = ['Field', 'Value'];
102
103         $tableFields = [
104             $this->trans('commands.user.create.messages.user-id'),
105             $this->trans('commands.user.create.messages.username'),
106             $this->trans('commands.user.create.messages.password'),
107             $this->trans('commands.user.create.messages.email'),
108             $this->trans('commands.user.create.messages.roles'),
109             $this->trans('commands.user.create.messages.created'),
110             $this->trans('commands.user.create.messages.status'),
111         ];
112
113         if ($user['success']) {
114             $tableData = array_map(
115                 function ($field, $value) {
116                     return [$field, $value];
117                 },
118                 $tableFields,
119                 $user['success']
120             );
121
122             $io->table($tableHeader, $tableData);
123             $io->success(
124                 sprintf(
125                     $this->trans('commands.user.create.messages.user-created'),
126                     $user['success']['username']
127                 )
128             );
129
130             return 0;
131         }
132
133         if ($user['error']) {
134             $io->error($user['error']['error']);
135         }
136     }
137
138     /**
139      * {@inheritdoc}
140      */
141     protected function interact(InputInterface $input, OutputInterface $output)
142     {
143         $io = new DrupalStyle($input, $output);
144
145         $username = $input->getArgument('username');
146         while (!$username) {
147             $username = $io->askEmpty(
148                 $this->trans('commands.user.create.questions.username'),
149                 null
150             );
151         }
152         $input->setArgument('username', $username);
153
154         $password = $input->getArgument('password');
155         if (!$password) {
156             $password = $io->askEmpty(
157                 $this->trans('commands.user.create.questions.password'),
158                 null
159             );
160         }
161         $input->setArgument('password', $password);
162
163         $roles = $input->getOption('roles');
164         if (!$roles) {
165             $systemRoles = $this->drupalApi->getRoles(false, false, false);
166             $roles = $io->choice(
167                 $this->trans('commands.user.create.questions.roles'),
168                 array_values($systemRoles),
169                 null,
170                 true
171             );
172
173             $roles = array_map(
174                 function ($role) use ($systemRoles) {
175                     return array_search($role, $systemRoles);
176                 },
177                 $roles
178             );
179
180             $input->setOption('roles', $roles);
181         }
182
183         $email = $input->getOption('email');
184         if (!$email) {
185             $email = $io->askEmpty(
186                 $this->trans('commands.user.create.questions.email'),
187                 null
188             );
189         }
190         $input->setOption('email', $email);
191
192         $status = $input->getOption('status');
193         if (!$status) {
194             $status = $io->choice(
195                 $this->trans('commands.user.create.questions.status'),
196                 [0, 1],
197                 1
198             );
199         }
200         $input->setOption('status', $status);
201     }
202
203     private function createUser($username, $password, $roles, $email = null, $status = null)
204     {
205         $password = $password?:$this->generatePassword();
206         $user = User::create(
207             [
208                 'name' => $username,
209                 'mail' => $email ?: $username . '@example.com',
210                 'pass' => $password,
211                 'status' => $status,
212                 'roles' => $roles,
213                 'created' => REQUEST_TIME,
214             ]
215         );
216
217         $result = [];
218
219         try {
220             $user->save();
221
222             $result['success'] = [
223                 'user-id' => $user->id(),
224                 'username' => $user->getUsername(),
225                 'password' => $password,
226                 'email' => $user->getEmail(),
227                 'roles' => implode(', ', $roles),
228                 'created' => $this->dateFormatter->format(
229                     $user->getCreatedTime(),
230                     'custom',
231                     'Y-m-d h:i:s'
232                 ),
233                 'status' => $status
234
235             ];
236         } catch (\Exception $e) {
237             $result['error'] = [
238                 'vid' => $user->id(),
239                 'name' => $user->get('name'),
240                 'error' => 'Error: ' . get_class($e) . ', code: ' . $e->getCode() . ', message: ' . $e->getMessage()
241             ];
242         }
243
244         return $result;
245     }
246
247     private function generatePassword()
248     {
249         $length = mt_rand(8, 16);
250         $str = '';
251
252         for ($i = 0; $i < $length; $i++) {
253             $str .= chr(mt_rand(32, 126));
254         }
255
256         return $str;
257     }
258 }