Completed
Push — master ( 96ea8b...1276b9 )
by Alexis
08:08
created

RoleCommand::interact()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 33
Code Lines 19

Duplication

Lines 33
Ratio 100 %

Importance

Changes 0
Metric Value
dl 33
loc 33
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 19
nc 8
nop 2
1
<?php
2
3
/*
4
 * This file is part of the awurth/silex-user package.
5
 *
6
 * (c) Alexis Wurth <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace AWurth\Silex\User\Command;
13
14
use AWurth\Silex\User\Util\UserManipulator;
15
use InvalidArgumentException;
16
use RuntimeException;
17
use Symfony\Component\Console\Input\InputArgument;
18
use Symfony\Component\Console\Input\InputInterface;
19
use Symfony\Component\Console\Input\InputOption;
20
use Symfony\Component\Console\Output\OutputInterface;
21
use Symfony\Component\Console\Question\Question;
22
23
/**
24
 * @author Lenar Lõhmus <[email protected]>
25
 */
26
abstract class RoleCommand extends ContainerAwareCommand
27
{
28
    /**
29
     * {@inheritdoc}
30
     */
31
    protected function configure()
32
    {
33
        $this
34
            ->setDefinition([
35
                new InputArgument('username', InputArgument::REQUIRED, 'The username'),
36
                new InputArgument('role', InputArgument::OPTIONAL, 'The role'),
37
                new InputOption('super', null, InputOption::VALUE_NONE, 'Instead specifying role, use this to quickly add the super administrator role')
38
            ]);
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    protected function execute(InputInterface $input, OutputInterface $output)
45
    {
46
        $username = $input->getArgument('username');
47
        $role = $input->getArgument('role');
48
        $super = (true === $input->getOption('super'));
49
50
        if (null !== $role && $super) {
51
            throw new InvalidArgumentException('You can pass either the role or the --super option (but not both simultaneously).');
52
        }
53
54
        if (null === $role && !$super) {
55
            throw new RuntimeException('Not enough arguments.');
56
        }
57
58
        $manipulator = $this->container['silex_user.util.user_manipulator'];
59
        $this->executeRoleCommand($manipulator, $output, $username, $super, $role);
60
    }
61
62
    /**
63
     * @see Command
64
     *
65
     * @param UserManipulator $manipulator
66
     * @param OutputInterface $output
67
     * @param string          $username
68
     * @param bool            $super
69
     * @param string          $role
70
     */
71
    abstract protected function executeRoleCommand(UserManipulator $manipulator, OutputInterface $output, $username, $super, $role);
72
73
    /**
74
     * {@inheritdoc}
75
     */
76 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...
77
    {
78
        $questions = [];
79
80
        if (!$input->getArgument('username')) {
81
            $question = new Question('Please choose a username:');
82
            $question->setValidator(function ($username) {
83
                if (empty($username)) {
84
                    throw new \Exception('Username can not be empty');
85
                }
86
87
                return $username;
88
            });
89
            $questions['username'] = $question;
90
        }
91
92
        if ((true !== $input->getOption('super')) && !$input->getArgument('role')) {
93
            $question = new Question('Please choose a role:');
94
            $question->setValidator(function ($role) {
95
                if (empty($role)) {
96
                    throw new \Exception('Role can not be empty');
97
                }
98
99
                return $role;
100
            });
101
            $questions['role'] = $question;
102
        }
103
104
        foreach ($questions as $name => $question) {
105
            $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...
106
            $input->setArgument($name, $answer);
107
        }
108
    }
109
}
110