Completed
Push — master ( affb41...f007be )
by Rafał
09:54
created

CreateUserCommand::interact()   B

Complexity

Conditions 8
Paths 16

Size

Total Lines 46

Duplication

Lines 34
Ratio 73.91 %

Importance

Changes 0
Metric Value
dl 34
loc 46
rs 7.9337
c 0
b 0
f 0
cc 8
nc 16
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher User Bundle.
7
 *
8
 * Copyright 2021 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @Copyright 2021 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\UserBundle\Command;
18
19
use SWP\Bundle\UserBundle\Util\UserManipulator;
20
use Symfony\Component\Console\Command\Command;
21
use Symfony\Component\Console\Input\InputArgument;
22
use Symfony\Component\Console\Input\InputInterface;
23
use Symfony\Component\Console\Input\InputOption;
24
use Symfony\Component\Console\Output\OutputInterface;
25
use Symfony\Component\Console\Question\Question;
26
27
class CreateUserCommand extends Command
28
{
29
    protected static $defaultName = 'swp:user:create';
30
31
    private $userManipulator;
32
33
    public function __construct(UserManipulator $userManipulator)
34
    {
35
        parent::__construct();
36
37
        $this->userManipulator = $userManipulator;
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    protected function configure()
44
    {
45
        $this
46
            ->setName('swp:user:create')
47
            ->setDescription('Create a user.')
48
            ->setDefinition([
49
                new InputArgument('username', InputArgument::REQUIRED, 'The username'),
50
                new InputArgument('email', InputArgument::REQUIRED, 'The email'),
51
                new InputArgument('password', InputArgument::REQUIRED, 'The password'),
52
                new InputOption('super-admin', null, InputOption::VALUE_NONE, 'Set the user as super admin'),
53
                new InputOption('inactive', null, InputOption::VALUE_NONE, 'Set the user as inactive'),
54
            ])
55
            ->setHelp(
56
                <<<'EOT'
57
The <info>swp:user:create</info> command creates a user:
58
59
  <info>php %command.full_name% matthieu</info>
60
61
This interactive shell will ask you for an email and then a password.
62
63
You can alternatively specify the email and password as the second and third arguments:
64
65
  <info>php %command.full_name% matthieu [email protected] mypassword</info>
66
67
You can create a super admin via the super-admin flag:
68
69
  <info>php %command.full_name% admin --super-admin</info>
70
71
You can create an inactive user (will not be able to log in):
72
73
  <info>php %command.full_name% thibault --inactive</info>
74
75
EOT
76
            );
77
    }
78
79
    /**
80
     * {@inheritdoc}
81
     */
82
    protected function execute(InputInterface $input, OutputInterface $output)
83
    {
84
        $username = $input->getArgument('username');
85
        $email = $input->getArgument('email');
86
        $password = $input->getArgument('password');
87
        $inactive = $input->getOption('inactive');
88
        $superadmin = $input->getOption('super-admin');
89
90
        $this->userManipulator->create($username, $password, $email, !$inactive, $superadmin);
0 ignored issues
show
Bug introduced by
It seems like $username defined by $input->getArgument('username') on line 84 can also be of type array<integer,string> or null; however, SWP\Bundle\UserBundle\Ut...erManipulator::create() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Bug introduced by
It seems like $password defined by $input->getArgument('password') on line 86 can also be of type array<integer,string> or null; however, SWP\Bundle\UserBundle\Ut...erManipulator::create() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Bug introduced by
It seems like $email defined by $input->getArgument('email') on line 85 can also be of type array<integer,string> or null; however, SWP\Bundle\UserBundle\Ut...erManipulator::create() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
91
92
        $output->writeln(sprintf('Created user <comment>%s</comment>', $username));
93
94
        return 0;
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    protected function interact(InputInterface $input, OutputInterface $output)
101
    {
102
        $questions = [];
103
104 View Code Duplication
        if (!$input->getArgument('username')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
            $question = new Question('Please choose a username:');
106
            $question->setValidator(function ($username) {
107
                if (empty($username)) {
108
                    throw new \Exception('Username can not be empty');
109
                }
110
111
                return $username;
112
            });
113
            $questions['username'] = $question;
114
        }
115
116 View Code Duplication
        if (!$input->getArgument('email')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
117
            $question = new Question('Please choose an email:');
118
            $question->setValidator(function ($email) {
119
                if (empty($email)) {
120
                    throw new \Exception('Email can not be empty');
121
                }
122
123
                return $email;
124
            });
125
            $questions['email'] = $question;
126
        }
127
128 View Code Duplication
        if (!$input->getArgument('password')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
129
            $question = new Question('Please choose a password:');
130
            $question->setValidator(function ($password) {
131
                if (empty($password)) {
132
                    throw new \Exception('Password can not be empty');
133
                }
134
135
                return $password;
136
            });
137
            $question->setHidden(true);
138
            $questions['password'] = $question;
139
        }
140
141
        foreach ($questions as $name => $question) {
142
            $answer = $this->getHelper('question')->ask($input, $output, $question);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method ask() does only exist in the following implementations of said interface: Symfony\Component\Console\Helper\QuestionHelper, Symfony\Component\Consol...r\SymfonyQuestionHelper.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
143
            $input->setArgument($name, $answer);
144
        }
145
    }
146
}
147