Completed
Push — master ( 274b6a...1a9054 )
by Sergi Tur
02:37
created

PublishAssignmentUsers   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 133
Duplicated Lines 100 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
dl 133
loc 133
rs 10
c 0
b 0
f 0
wmc 10
lcom 1
cbo 5

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 5 5 1
A handle() 9 9 2
A assignUsersToAssignment() 21 21 3
A users() 17 17 2
A askForUsers() 13 13 1
A abortCommandExecution() 4 4 1

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 Acacha\ForgePublish\Commands;
4
5
use Acacha\ForgePublish\Commands\Traits\AborstIfEnvVariableIsnotInstalled;
6
use Acacha\ForgePublish\Commands\Traits\InteractsWithEnvironment;
7
use Acacha\ForgePublish\Commands\Traits\InteractsWithLocalGithub;
8
use GuzzleHttp\Client;
9
use Illuminate\Console\Command;
10
11
/**
12
 * Class PublishAssignmentUsers.
13
 *
14
 * @package Acacha\ForgePublish\Commands
15
 */
16 View Code Duplication
class PublishAssignmentUsers extends Command
0 ignored issues
show
Duplication introduced by
This class 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...
17
{
18
    use InteractsWithLocalGithub, InteractsWithEnvironment;
19
20
    use AborstIfEnvVariableIsnotInstalled;
21
22
    /**
23
     * The name and signature of the console command.
24
     *
25
     * @var string
26
     */
27
    protected $signature = 'publish:assignment_users {--user=* : The user/s assigned to this assignment}';
28
29
    /**
30
     * The console command description.
31
     *
32
     * @var string
33
     */
34
    protected $description = 'Assing users to current assignment';
35
36
    /**
37
     * Server names.
38
     *
39
     * @var Client
40
     */
41
    protected $http;
42
43
    /**
44
     * Users.
45
     *
46
     * @var array
47
     */
48
    protected $users;
49
50
    /**
51
     * SaveEnvVariable constructor.
52
     *
53
     */
54
    public function __construct(Client $http)
55
    {
56
        parent::__construct();
57
        $this->http = $http;
58
    }
59
60
    /**
61
     * Execute the console command.
62
     *
63
     */
64
    public function handle()
65
    {
66
        $this->abortCommandExecution();
67
68
        $this->users = $this->option('user') ? $this->argument('user') : $this->askForUsers();
69
70
        $this->assignUsersToAssignment();
71
72
    }
73
74
    /**
75
     * Assign users to assignment
76
     *
77
     * @return array|mixed
78
     */
79
    protected function assignUsersToAssignment()
80
    {
81
        $assignment = fp_env('ACACHA_FORGE_ASSIGNMENT');
82
        foreach ( $this->users as $user) {
83
            $uri = str_replace('{assignment}', $assignment, config('forge-publish.assign_user_to_assignment_uri'));
84
            $uri = str_replace('{user}', $user, $uri);
85
            $url = config('forge-publish.url') . $uri;
86
            try {
87
                $response = $this->http->post($url, [
0 ignored issues
show
Unused Code introduced by
$response is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
88
                    'headers' => [
89
                        'X-Requested-With' => 'XMLHttpRequest',
90
                        'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
91
                    ]
92
                ]);
93
            } catch (\Exception $e) {
94
                $this->error('And error occurs connecting to the api url: ' . $url);
95
                $this->error('Status code: ' . $e->getResponse()->getStatusCode() . ' | Reason : ' . $e->getResponse()->getReasonPhrase());
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Exception as the method getResponse() does only exist in the following sub-classes of Exception: GuzzleHttp\Exception\BadResponseException, GuzzleHttp\Exception\ClientException, GuzzleHttp\Exception\ConnectException, GuzzleHttp\Exception\RequestException, GuzzleHttp\Exception\ServerException, GuzzleHttp\Exception\TooManyRedirectsException. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
96
                return;
97
            }
98
        }
99
    }
100
101
    /**
102
     * Get users
103
     */
104
    protected function users()
105
    {
106
        $url = config('forge-publish.url') . config('forge-publish.list_users_uri');
107
        try {
108
            $response = $this->http->get($url, [
109
                'headers' => [
110
                    'X-Requested-With' => 'XMLHttpRequest',
111
                    'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
112
                ]
113
            ]);
114
        } catch (\Exception $e) {
115
            $this->error('And error occurs connecting to the api url: ' . $url);
116
            $this->error('Status code: ' . $e->getResponse()->getStatusCode() . ' | Reason : ' . $e->getResponse()->getReasonPhrase());
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Exception as the method getResponse() does only exist in the following sub-classes of Exception: GuzzleHttp\Exception\BadResponseException, GuzzleHttp\Exception\ClientException, GuzzleHttp\Exception\ConnectException, GuzzleHttp\Exception\RequestException, GuzzleHttp\Exception\ServerException, GuzzleHttp\Exception\TooManyRedirectsException. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
117
            return [];
118
        }
119
        return json_decode((string) $response->getBody());
120
    }
121
122
    /**
123
     * Ask for users.
124
     *
125
     * @return string
126
     */
127
    protected function askForUsers()
128
    {
129
        $default = 0;
130
        $users = $this->users();
131
        $user_names = collect($users)->pluck('name')->toArray();
132
        $selected_user_names =  $this->choice('Users?', $user_names ,$default, null, true);
133
134
        $users = collect($users)->filter(function ($user) use ($selected_user_names) {
135
            return in_array($user->name,$selected_user_names);
136
        });
137
138
        return $users->pluck('id');
139
    }
140
141
    /**
142
     * Abort command execution.
143
     */
144
    protected function abortCommandExecution()
145
    {
146
        $this->abortsIfEnvVarIsNotInstalled('ACACHA_FORGE_ASSIGNMENT');
147
    }
148
}
149