Completed
Pull Request — master (#2737)
by Jeroen
10:25
created

RoleCommand::interact()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 33

Duplication

Lines 33
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
dl 33
loc 33
ccs 0
cts 20
cp 0
rs 8.4586
c 0
b 0
f 0
cc 7
nc 8
nop 2
crap 56
1
<?php
2
3
namespace Kunstmaan\AdminBundle\Command;
4
5
use FOS\UserBundle\Model\UserManager as FOSUserManager;
6
use InvalidArgumentException;
7
use Kunstmaan\AdminBundle\Service\UserManager;
8
use RuntimeException;
9
use Symfony\Component\Console\Command\Command;
10
use Symfony\Component\Console\Input\InputArgument;
11
use Symfony\Component\Console\Input\InputInterface;
12
use Symfony\Component\Console\Input\InputOption;
13
use Symfony\Component\Console\Output\OutputInterface;
14
use Symfony\Component\Console\Question\Question;
15
16
abstract class RoleCommand extends Command
17
{
18
    /** @var FOSUserManager|UserManager */
19
    protected $userManager;
20
21 View Code Duplication
    public function __construct(/* UserManager */ $userManager)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
22
    {
23
        parent::__construct();
24
25
        if (!$userManager instanceof UserManager && !$userManager instanceof FOSUserManager) {
26
            throw new InvalidArgumentException(sprintf('The "$userManager" argument must be of type "%s" or type "%s"', UserManager::class, FOSUserManager::class));
27
        }
28
        if ($userManager instanceof FOSUserManager) {
29
            // NEXT_MAJOR set the usermanaged typehint to the kunstmaan usermanager.
30
            @trigger_error(sprintf('Passing the usermanager from FOSUserBundle as the first argument of "%s" is deprecated since KunstmaanAdminBundle 5.8 and will be removed in KunstmaanAdminBundle 6.0. Use the new Kunstmaan Usermanager %s.', __METHOD__, UserManager::class), E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
31
        }
32
33
        $this->userManager = $userManager;
34
    }
35
36
    protected function configure()
37
    {
38
        $this
39
            ->setDefinition([
40
                new InputArgument('username', InputArgument::REQUIRED, 'The username'),
41
                new InputArgument('role', InputArgument::OPTIONAL, 'The role'),
42
                new InputOption('super', null, InputOption::VALUE_NONE, 'Instead specifying role, use this to quickly add the super administrator role'),
43
            ]);
44
    }
45
46
    protected function execute(InputInterface $input, OutputInterface $output)
47
    {
48
        $username = $input->getArgument('username');
49
        $role = $input->getArgument('role');
50
        $super = (true === $input->getOption('super'));
51
52
        if (null !== $role && $super) {
53
            throw new InvalidArgumentException('You can pass either the role or the --super option (but not both simultaneously).');
54
        }
55
56
        if (null === $role && !$super) {
57
            throw new RuntimeException('Not enough arguments.');
58
        }
59
60
        $this->executeRoleCommand($output, $username, $super, $role);
61
    }
62
63
    abstract protected function executeRoleCommand(OutputInterface $output, $username, $super, $role);
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
64
65 View Code Duplication
    protected function interact(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
66
    {
67
        $questions = [];
68
69
        if (!$input->getArgument('username')) {
70
            $question = new Question('Please choose a username:');
71
            $question->setValidator(function ($username) {
72
                if (empty($username)) {
73
                    throw new InvalidArgumentException('Username can not be empty');
74
                }
75
76
                return $username;
77
            });
78
            $questions['username'] = $question;
79
        }
80
81
        if ((true !== $input->getOption('super')) && !$input->getArgument('role')) {
82
            $question = new Question('Please choose a role:');
83
            $question->setValidator(function ($role) {
84
                if (empty($role)) {
85
                    throw new InvalidArgumentException('Role can not be empty');
86
                }
87
88
                return $role;
89
            });
90
            $questions['role'] = $question;
91
        }
92
93
        foreach ($questions as $name => $question) {
94
            $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: Sensio\Bundle\GeneratorB...d\Helper\QuestionHelper, 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...
95
            $input->setArgument($name, $answer);
96
        }
97
    }
98
}
99