Completed
Push — master ( ad54cf...a5bc07 )
by Alexis
01:49
created

CreateUserCommand   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 117
Duplicated Lines 30.77 %

Coupling/Cohesion

Components 2
Dependencies 6

Importance

Changes 0
Metric Value
wmc 12
lcom 2
cbo 6
dl 36
loc 117
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A configure() 0 12 1
B execute() 0 26 2
C interact() 36 48 8

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace App\Command;
4
5
use Cartalyst\Sentinel\Sentinel;
6
use Symfony\Component\Console\Command\Command;
7
use Symfony\Component\Console\Input\InputArgument;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Input\InputOption;
10
use Symfony\Component\Console\Output\OutputInterface;
11
use Symfony\Component\Console\Question\Question;
12
13
class CreateUserCommand extends Command
14
{
15
    /**
16
     * @var Sentinel
17
     */
18
    private $sentinel;
19
20
    /**
21
     * Constructor.
22
     *
23
     * @param Sentinel $sentinel
24
     */
25
    public function __construct(Sentinel $sentinel)
26
    {
27
        parent::__construct();
28
29
        $this->sentinel = $sentinel;
30
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    protected function configure()
36
    {
37
        $this
38
            ->setName('user:create')
39
            ->setDescription('Create new user')
40
            ->setDefinition([
41
                new InputArgument('username', InputArgument::REQUIRED, 'The username'),
42
                new InputArgument('email', InputArgument::REQUIRED, 'The email'),
43
                new InputArgument('password', InputArgument::REQUIRED, 'The password'),
44
                new InputOption('admin', null, InputOption::VALUE_NONE, 'Set the user as admin')
45
            ]);
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    protected function execute(InputInterface $input, OutputInterface $output)
52
    {
53
        $username = $input->getArgument('username');
54
        $email = $input->getArgument('email');
55
        $password = $input->getArgument('password');
56
        $admin = $input->getOption('admin');
57
58
        if ($admin) {
59
            $role = $this->sentinel->findRoleByName('Admin');
60
        } else {
61
            $role = $this->sentinel->findRoleByName('User');
62
        }
63
64
        $user = $this->sentinel->registerAndActivate([
65
            'username' => $username,
66
            'email' => $email,
67
            'password' => $password,
68
            'permissions' => [
69
                'user.delete' => 0
70
            ]
71
        ]);
72
73
        $role->users()->attach($user);
74
75
        return 0;
76
    }
77
78
    /**
79
     * {@inheritdoc}
80
     */
81
    protected function interact(InputInterface $input, OutputInterface $output)
82
    {
83
        $questions = [];
84
85 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...
86
            $question = new Question('Please choose a username:');
87
            $question->setValidator(function ($username) {
88
                if (empty($username)) {
89
                    throw new \Exception('Username can not be empty');
90
                }
91
92
                return $username;
93
            });
94
            $questions['username'] = $question;
95
        }
96
97 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...
98
            $question = new Question('Please choose an email:');
99
            $question->setValidator(function ($email) {
100
                if (empty($email)) {
101
                    throw new \Exception('Email can not be empty');
102
                }
103
104
                return $email;
105
            });
106
107
            $questions['email'] = $question;
108
        }
109
110 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...
111
            $question = new Question('Please choose a password:');
112
            $question->setValidator(function ($password) {
113
                if (empty($password)) {
114
                    throw new \Exception('Password can not be empty');
115
                }
116
117
                return $password;
118
            });
119
120
            $question->setHidden(true);
121
            $questions['password'] = $question;
122
        }
123
124
        foreach ($questions as $name => $question) {
125
            $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...
126
            $input->setArgument($name, $answer);
127
        }
128
    }
129
}
130