From 4cea1ec6ffc41e6ca6b7874b42e4886b94147fae Mon Sep 17 00:00:00 2001 From: Julian SCARPONE Date: Tue, 28 May 2019 15:46:23 +0200 Subject: [PATCH] Command, allow to search User by Email --- src/Jwt/Command/JwtGeneratorCommand.php | 75 ++++++++++++++++++++----- 1 file changed, 60 insertions(+), 15 deletions(-) diff --git a/src/Jwt/Command/JwtGeneratorCommand.php b/src/Jwt/Command/JwtGeneratorCommand.php index 8250775..70c1104 100644 --- a/src/Jwt/Command/JwtGeneratorCommand.php +++ b/src/Jwt/Command/JwtGeneratorCommand.php @@ -35,6 +35,7 @@ protected function configure() ->setName('biig:jwt:generate') ->setDescription('Generate the first user JWT Token.') ->addOption('role', 'r', InputOption::VALUE_OPTIONAL, 'Specify what role you want') + ->addOption('email', null, InputOption::VALUE_OPTIONAL, 'Specify what email the user should have') ->setHelp(<<hasOption('role') + if ($input->hasOption('email') + && null !== $input->getOption('email')) + { + $user = $this->findByEmail($input->getOption('email'), $output, $user, $users); + } + else if ($input->hasOption('role') && null !== $input->getOption('role') - && !in_array($input->getOption('role'), $user->getRoles()) - ) { - $find = false; - foreach ($users as $item) { - if (in_array($input->getOption('role'), $item->getRoles())) { - $user = $item; - $find = true; - } - } - - if (!$find) { - $output->writeln(sprintf('User with role "%s" doesn\'t exist.', $input->getOption('role'))); + && !in_array($input->getOption('role'), $user->getRoles())) + { + $user = $this->findOneByRole($input, $output, $users); + } - return; - } + if ($user === null) { + return ; } $token = $this->generator->create($user); @@ -89,4 +87,51 @@ protected function execute(InputInterface $input, OutputInterface $output) 'Token: ' . $token, ]); } + + /** + * @param string $email + * @param OutputInterface $output + * @param $user + * @param array $users + * + * @return mixed + */ + private function findByEmail(string $email, OutputInterface $output, $user, array $users) + { + if (!method_exists($user, 'getEmail')) { + $output->writeln('User Class does not have a getEmail() method'); + + return null; + } + + foreach ($users as $item) { + if ($email === $item->getEmail()) { + return $item; + } + } + + $output->writeln(sprintf('User with email "%s" doesn\'t exist.', $input->getOption('email'))); + + return null; + } + + /** + * @param string $role + * @param OutputInterface $output + * @param array $users + * + * @return mixed + */ + protected function findOneByRole(string $role, OutputInterface $output, array $users) + { + foreach ($users as $item) { + if (in_array($role, $item->getRoles())) { + return $item; + } + } + + $output->writeln(sprintf('User with role "%s" doesn\'t exist.', $role)); + + return null; + } }