Completed
Push — master ( f0c745...274b6a )
by Sergi Tur
01:40
created

PublishAssignment::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
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 PublishAssignment.
13
 *
14
 * @package Acacha\ForgePublish\Commands
15
 */
16
class PublishAssignment extends Command
17
{
18
19
    use InteractsWithLocalGithub, InteractsWithEnvironment;
20
21
    use AborstIfEnvVariableIsnotInstalled;
22
23
    /**
24
     * The name and signature of the console command.
25
     *
26
     * @var string
27
     */
28
    protected $signature = 'publish:assignment {name? : The name description} {repository_uri? : The repository URI} {repository_type? : The repository type} {forge_site? : The Laravel Forge site id} {forge_server? : The Laravel Forge Server} ';
29
30
    /**
31
     * The console command description.
32
     *
33
     * @var string
34
     */
35
    protected $description = 'Create a new assignment using current project';
36
37
    /**
38
     * Server names.
39
     *
40
     * @var Client
41
     */
42
    protected $http;
43
44
    /**
45
     * Assignment name.
46
     *
47
     * @var String
48
     */
49
    protected $assignmentName;
50
51
    /**
52
     * Repository uri.
53
     *
54
     * @var String
55
     */
56
    protected $repository_uri;
57
58
    /**
59
     * Repository type.
60
     *
61
     * @var String
62
     */
63
    protected $repository_type;
64
65
    /**
66
     * Laravel Forge site id.
67
     *
68
     * @var String
69
     */
70
    protected $forge_site;
71
72
    /**
73
     * Existing assignment
74
     * @var
75
     */
76
    protected $existingAssignment;
77
78
    /**
79
     * Laravel Forge server id.
80
     *
81
     * @var String
82
     */
83
    protected $forge_server;
84
85
    /**
86
     * SaveEnvVariable constructor.
87
     *
88
     */
89
    public function __construct(Client $http)
90
    {
91
        parent::__construct();
92
        $this->http = $http;
93
    }
94
95
    /**
96
     * Execute the console command.
97
     *
98
     */
99
    public function handle()
100
    {
101
        $this->abortCommandExecution();
102
103
        $this->assignmentName = $this->argument('name') ? $this->argument('name') : $this->askName();
104
105
        $this->repository_uri = $this->argument('repository_uri') ? $this->argument('repository_uri') : $this->askRepositoryUri();
106
        $this->repository_type = $this->argument('repository_type') ? $this->argument('repository_type') : $this->askRepositoryType();
107
        $this->forge_site = $this->argument('forge_site') ? $this->argument('forge_site') : $this->askForgeSite();
108
        $this->forge_server = $this->argument('forge_server') ? $this->argument('forge_server') : $this->askForgeServer();
109
110
        $this->existingAssignment = fp_env('ACACHA_FORGE_ASSIGNMENT');
111
        dd($this->existingAssignment);
112
        if (! $this->existingAssignment) {
113
            $this->createAssignment();
114
        } else {
115
            $this->info('An assignment with id : ' . $this->existingAssignment . 'Already exists! Updating...' );
116
            $this->updateAssignment();
117
        }
118
119
        $this->info('Assignment created ok!');
120
    }
121
122
    /**
123
     * Create assignment.
124
     *
125
     * @return array|mixed
126
     */
127 View Code Duplication
    protected function createAssignment()
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...
128
    {
129
        $url = config('forge-publish.url') . config('forge-publish.store_assignment_uri');
130
        try {
131
            $response = $this->http->post($url, [
132
                'form_params' => [
133
                    'name' => $this->assignmentName,
134
                    'repository_uri' => $this->repository_uri,
135
                    'repository_type' => $this->repository_type,
136
                    'forge_site' => $this->forge_site,
137
                    'forge_server' => $this->forge_server
138
                ],
139
                'headers' => [
140
                    'X-Requested-With' => 'XMLHttpRequest',
141
                    'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
142
                ]
143
            ]);
144
        } catch (\Exception $e) {
145
            dd($e);
146
            $this->error('And error occurs connecting to the api url: ' . $url);
147
            $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...
148
            return [];
149
        }
150
        $assignment = json_decode((string) $response->getBody());
151
        dump($assignment);
152
        $this->addValueToEnv('ACACHA_FORGE_ASSIGNMENT', $assignment->id);
153
        return $assignment;
154
    }
155
156
    /**
157
     * Update assignment.
158
     *
159
     * @return array|mixed
160
     */
161 View Code Duplication
    protected function updateAssignment()
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...
162
    {
163
        $uri = str_replace('{assignment}', $this->existingAssignment, config('forge-publish.update_assignment_uri'));
164
        $url = config('forge-publish.url') . $uri;
165
        dd($url);
166
        try {
167
            $response = $this->http->post($url, [
168
                'form_params' => [
169
                    'name' => $this->assignmentName,
170
                    'repository_uri' => $this->repository_uri,
171
                    'repository_type' => $this->repository_type,
172
                    'forge_site' => $this->forge_site,
173
                    'forge_server' => $this->forge_server
174
                ],
175
                'headers' => [
176
                    'X-Requested-With' => 'XMLHttpRequest',
177
                    'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
178
                ]
179
            ]);
180
        } catch (\Exception $e) {
181
            dd($e);
182
            $this->error('And error occurs connecting to the api url: ' . $url);
183
            $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...
184
            return [];
185
        }
186
        return json_decode((string) $response->getBody());
187
    }
188
189
    /**
190
     * Ask forge site.
191
     *
192
     * @return string
193
     */
194
    protected function askForgeSite()
195
    {
196
        $default = $this->defaultForgeSite();
197
        return $this->ask('Forge site?',$default);
198
    }
199
200
    /**
201
     * Ask forge server.
202
     *
203
     * @return string
204
     */
205
    protected function askForgeServer()
206
    {
207
        $default = $this->defaultForgeServer();
208
        return $this->ask('Forge server?',$default);
209
    }
210
211
    /**
212
     * Default forge site
213
     */
214
    protected function defaultForgeSite()
215
    {
216
        return fp_env('ACACHA_FORGE_SITE') ? fp_env('ACACHA_FORGE_SITE') : null;
217
    }
218
219
    /**
220
     * Default forge server.
221
     */
222
    protected function defaultForgeServer()
223
    {
224
        return fp_env('ACACHA_FORGE_SERVER') ? fp_env('ACACHA_FORGE_SERVER') : null;
225
    }
226
227
    /**
228
     * Ask name.
229
     */
230
    protected function askName()
231
    {
232
        $default = $this->defaultName();
233
        return $this->ask('name?',$default);
234
    }
235
236
    /**
237
     * Ask repository Uri.
238
     */
239
    protected function askRepositoryUri() {
240
        $default = $this->defaultRepositoryUri();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $default is correct as $this->defaultRepositoryUri() (which targets Acacha\ForgePublish\Comm...:defaultRepositoryUri()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
241
        return $this->ask('Repository URI?', $default);
242
    }
243
244
    /**
245
     * Ask repository Uri.
246
     */
247
    protected function askRepositoryType() {
248
        $default = $this->defaultRepositoryType();
249
        return $this->ask('Repository type?', $default);
250
    }
251
252
    /**
253
     * Default repository type.
254
     *
255
     * @return string
256
     */
257
    protected function defaultRepositoryType()
258
    {
259
        return 'github';
260
    }
261
262
    /**
263
     * Default repository URI.
264
     *
265
     * @return null
266
     */
267
    protected function defaultRepositoryUri()
268
    {
269
        return fp_env('ACACHA_FORGE_GITHUB_REPO') ? fp_env('ACACHA_FORGE_GITHUB_REPO') : $this->getRepoFromGithubConfig();
270
    }
271
272
    /**
273
     * Default name.
274
     *
275
     * @return null|string
276
     */
277
    protected function defaultName()
278
    {
279
        return fp_env('ACACHA_FORGE_DOMAIN') ? fp_env('ACACHA_FORGE_DOMAIN') : strtolower(camel_case(basename(getcwd())));
280
    }
281
282
    /**
283
     * Abort command execution.
284
     */
285
    protected function abortCommandExecution()
286
    {
287
        $this->abortsIfEnvVarIsNotInstalled('ACACHA_FORGE_ACCESS_TOKEN');
288
    }
289
}
290