GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#129)
by Chris
01:53
created

Server::confirmResize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php declare(strict_types=1);
2
3
namespace OpenStack\Compute\v2\Models;
4
5
use OpenStack\Common\Resource\HasWaiterTrait;
6
use OpenStack\Common\Resource\Creatable;
7
use OpenStack\Common\Resource\Deletable;
8
use OpenStack\Common\Resource\Listable;
9
use OpenStack\Common\Resource\Retrievable;
10
use OpenStack\Common\Resource\Updateable;
11
use OpenStack\Common\Resource\OperatorResource;
12
use OpenStack\Common\Transport\Utils;
13
use OpenStack\BlockStorage\v2\Models\VolumeAttachment;
14
use OpenStack\Compute\v2\Enum;
15
use OpenStack\Networking\v2\Extensions\SecurityGroups\Models\SecurityGroup;
16
use Psr\Http\Message\ResponseInterface;
17
18
/**
19
 * @property \OpenStack\Compute\v2\Api $api
20
 */
21
class Server extends OperatorResource implements
22
    Creatable,
23
    Updateable,
24
    Deletable,
25
    Retrievable,
26
    Listable
27
{
28
    use HasWaiterTrait;
29
30
    /** @var string */
31
    public $id;
32
33
    /** @var string */
34
    public $ipv4;
35
36
    /** @var string */
37
    public $ipv6;
38
39
    /** @var array */
40
    public $addresses;
41
42
    /** @var \DateTimeImmutable */
43
    public $created;
44
45
    /** @var \DateTimeImmutable */
46
    public $updated;
47
48
    /** @var Flavor */
49
    public $flavor;
50
51
    /** @var string */
52
    public $hostId;
53
54
    /** @var string */
55
    public $hypervisorHostname;
56
57
    /** @var Image */
58
    public $image;
59
60
    /** @var array */
61
    public $links;
62
63
    /** @var array */
64
    public $metadata;
65
66
    /** @var string */
67
    public $name;
68
69
    /** @var string */
70
    public $progress;
71
72
    /** @var string */
73
    public $status;
74
75
    /** @var string */
76
    public $tenantId;
77
78
    /** @var string */
79
    public $userId;
80
81
    /** @var string */
82
    public $adminPass;
83
84
    /** @var string */
85
    public $taskState;
86
87
    protected $resourceKey = 'server';
88
    protected $resourcesKey = 'servers';
89
    protected $markerKey = 'id';
90
91
    protected $aliases = [
92
        'block_device_mapping_v2'             => 'blockDeviceMapping',
93
        'accessIPv4'                          => 'ipv4',
94
        'accessIPv6'                          => 'ipv6',
95
        'tenant_id'                           => 'tenantId',
96
        'user_id'                             => 'userId',
97
        'security_groups'                     => 'securityGroups',
98
        'OS-EXT-STS:task_state'               => 'taskState',
99
        'OS-EXT-SRV-ATTR:hypervisor_hostname' => 'hypervisorHostname',
100
    ];
101 2
102
    /**
103 2
     * {@inheritDoc}
104 2
     *
105
     * @param array $userOptions {@see \OpenStack\Compute\v2\Api::postServer}
106
     */
107
    public function create(array $userOptions): Creatable
108
    {
109
        $response = $this->execute($this->api->postServer(), $userOptions);
110 1
        return $this->populateFromResponse($response);
111
    }
112 1
113
    /**
114 1
     * {@inheritDoc}
115
     */
116
    public function update()
117
    {
118
        $response = $this->execute($this->api->putServer(), $this->getAttrs(['id', 'name', 'ipv4', 'ipv6']));
119
        $this->populateFromResponse($response);
120 1
    }
121
122 1
    /**
123 1
     * {@inheritDoc}
124
     */
125
    public function delete()
126
    {
127
        $this->execute($this->api->deleteServer(), $this->getAttrs(['id']));
128 1
    }
129
130 1
    /**
131
     * {@inheritDoc}
132 1
     */
133
    public function retrieve()
134
    {
135
        $response = $this->execute($this->api->getServer(), $this->getAttrs(['id']));
136
        $this->populateFromResponse($response);
137
    }
138
139
    /**
140 1
     * Changes the root password for a server.
141
     *
142 1
     * @param string $newPassword The new root password
143 1
     */
144
    public function changePassword(string $newPassword)
145 1
    {
146 1
        $this->execute($this->api->changeServerPassword(), [
147
            'id'       => $this->id,
148
            'password' => $newPassword,
149
        ]);
150
    }
151
152
    /**
153 2
     * Reboots the server.
154
     *
155 2
     * @param string $type The type of reboot that will be performed. Either SOFT or HARD is supported.
156 1
     */
157
    public function reboot(string $type = Enum::REBOOT_SOFT)
158
    {
159 1
        if (!in_array($type, ['SOFT', 'HARD'])) {
160 1
            throw new \RuntimeException('Reboot type must either be SOFT or HARD');
161 1
        }
162 1
163 1
        $this->execute($this->api->rebootServer(), [
164
            'id'   => $this->id,
165
            'type' => $type,
166
        ]);
167
    }
168
169
    /**
170 1
     * Starts server
171
     */
172 1
    public function start()
173 1
    {
174
        $this->execute($this->api->startServer(), [
175 1
            'id' => $this->id,
176 1
            'os-start' => null
177
        ]);
178
    }
179
180
    /**
181
     * Stops server
182
     */
183
    public function stop()
184 1
    {
185
        $this->execute($this->api->stopServer(), [
186 1
            'id' => $this->id,
187 1
            'os-stop' => null
188 1
        ]);
189 1
    }
190
191 1
    /**
192 1
     * Rebuilds the server.
193
     *
194
     * @param array $options {@see \OpenStack\Compute\v2\Api::rebuildServer}
195
     */
196
    public function rebuild(array $options)
197 1
    {
198
        $options['id'] = $this->id;
199 1
        $response = $this->execute($this->api->rebuildServer(), $options);
200 1
201
        $this->populateFromResponse($response);
202
    }
203
204
    /**
205 1
     * Resizes the server to a new flavor. Once this operation is complete and server has transitioned
206
     * to an active state, you will either need to call {@see confirmResize()} or {@see revertResize()}.
207 1
     *
208 1
     * @param string $flavorId The UUID of the new flavor your server will be based on.
209
     */
210
    public function resize(string $flavorId)
211
    {
212
        $response = $this->execute($this->api->resizeServer(), [
213
            'id'       => $this->id,
214
            'flavorId' => $flavorId,
215 1
        ]);
216
217 1
        $this->populateFromResponse($response);
218 1
    }
219 1
220
    /**
221
     * Confirms a previous resize operation.
222
     */
223
    public function confirmResize()
224
    {
225
        $this->execute($this->api->confirmServerResize(), ['confirmResize' => null, 'id' => $this->id]);
226
    }
227
228 2
    /**
229
     * Reverts a previous resize operation.
230 2
     */
231
    public function revertResize()
232 2
    {
233 2
        $this->execute($this->api->revertServerResize(), ['revertResize' => null, 'id' => $this->id]);
234 2
    }
235
236
    /**
237
     * Gets a VNC console for a server.
238
     *
239
     * @param  string $type The type of VNC console: novnc|xvpvnc.
240
     *                      Defaults to novnc.
241
     *
242 1
     * @return array
243
     */
244 1
    public function getVncConsole($type = Enum::CONSOLE_NOVNC): array
245 1
    {
246
        $response = $this->execute($this->api->getVncConsole(), ['id' => $this->id, 'type' => $type]);
247
        return Utils::jsonDecode($response)['console'];
248
    }
249
250
    /**
251
     * Gets a RDP console for a server.
252
     *
253
     * @param  string $type The type of VNC console: rdp-html5 (default).
254
     *
255
     * @return array
256 1
     */
257
    public function getRDPConsole($type = Enum::CONSOLE_RDP_HTML5): array
258 1
    {
259 1
        $response = $this->execute($this->api->getRDPConsole(), ['id' => $this->id, 'type' => $type]);
260
        return Utils::jsonDecode($response)['console'];
261
    }
262
263
    /**
264
     * Gets a Spice console for a server.
265
     *
266
     * @param  string $type The type of VNC console: spice-html5.
267
     *
268
     * @return array
269
     */
270
    public function getSpiceConsole($type = Enum::CONSOLE_SPICE_HTML5): array
271 1
    {
272
        $response = $this->execute($this->api->getSpiceConsole(), ['id' => $this->id, 'type' => $type]);
273 1
        return Utils::jsonDecode($response)['console'];
274 1
    }
275
276
    /**
277
     * Gets a serial console for a server.
278
     *
279
     * @param  string $type The type of VNC console: serial.
280
     *
281
     * @return array
282
     */
283
    public function getSerialConsole($type = Enum::CONSOLE_SERIAL): array
284 1
    {
285
        $response = $this->execute($this->api->getSerialConsole(), ['id' => $this->id, 'type' => $type]);
286 1
        return Utils::jsonDecode($response)['console'];
287 1
    }
288
289
    /**
290
     * Creates an image for the current server.
291
     *
292
     * @param array $options {@see \OpenStack\Compute\v2\Api::createServerImage}
293
     */
294
    public function createImage(array $options)
295 1
    {
296
        $options['id'] = $this->id;
297 1
        $this->execute($this->api->createServerImage(), $options);
298 1
    }
299
300
    /**
301
     * Iterates over all the IP addresses for this server.
302
     *
303
     * @param array $options {@see \OpenStack\Compute\v2\Api::getAddressesByNetwork}
304
     *
305
     * @return array An array containing to two keys: "public" and "private"
306
     */
307
    public function listAddresses(array $options = []): array
308
    {
309
        $options['id'] = $this->id;
310
311
        $data = (isset($options['networkLabel'])) ? $this->api->getAddressesByNetwork() : $this->api->getAddresses();
312
        $response = $this->execute($data, $options);
313
        return Utils::jsonDecode($response)['addresses'];
314
    }
315
316
    /**
317
     * Iterates over all the ports for this server.
318
     *
319
     * @return array
320
     */
321
    public function listPorts(array $options = []): array
322
    {
323
        $options['id'] = $this->id;
324
325
        $response = $this->execute($this->api->getPorts(), ['id' => $this->id]);
326
        return Utils::jsonDecode($response)['interfaceAttachments'];
327
    }
328
329
    /**
330
     * Retrieves metadata from the API.
331
     *
332
     * @return array
333
     */
334
    public function getMetadata(): array
335
    {
336
        $response = $this->execute($this->api->getServerMetadata(), ['id' => $this->id]);
337
        return $this->parseMetadata($response);
338
    }
339
340
    /**
341
     * Resets all the metadata for this server with the values provided. All existing metadata keys
342
     * will either be replaced or removed.
343
     *
344
     * @param array $metadata {@see \OpenStack\Compute\v2\Api::putServerMetadata}
345
     */
346
    public function resetMetadata(array $metadata)
347
    {
348
        $response = $this->execute($this->api->putServerMetadata(), ['id' => $this->id, 'metadata' => $metadata]);
349
        $this->metadata = $this->parseMetadata($response);
350
    }
351
352
    /**
353
     * Merges the existing metadata for the server with the values provided. Any existing keys
354
     * referenced in the user options will be replaced with the user's new values. All other
355
     * existing keys will remain unaffected.
356
     *
357
     * @param array $metadata {@see \OpenStack\Compute\v2\Api::postServerMetadata}
358
     *
359
     * @return array
360
     */
361
    public function mergeMetadata(array $metadata)
362
    {
363
        $response = $this->execute($this->api->postServerMetadata(), ['id' => $this->id, 'metadata' => $metadata]);
364
        $this->metadata = $this->parseMetadata($response);
365
    }
366
367
    /**
368
     * Retrieve the value for a specific metadata key.
369
     *
370
     * @param string $key {@see \OpenStack\Compute\v2\Api::getServerMetadataKey}
371
     *
372
     * @return mixed
373
     */
374 View Code Duplication
    public function getMetadataItem(string $key)
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...
375
    {
376
        $response = $this->execute($this->api->getServerMetadataKey(), ['id' => $this->id, 'key' => $key]);
377
        $value = $this->parseMetadata($response)[$key];
378
        $this->metadata[$key] = $value;
379
        return $value;
380
    }
381
382
    /**
383
     * Remove a specific metadata key.
384
     *
385
     * @param string $key {@see \OpenStack\Compute\v2\Api::deleteServerMetadataKey}
386
     */
387 View Code Duplication
    public function deleteMetadataItem(string $key)
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...
388
    {
389
        if (isset($this->metadata[$key])) {
390
            unset($this->metadata[$key]);
391
        }
392
393
        $this->execute($this->api->deleteServerMetadataKey(), ['id' => $this->id, 'key' => $key]);
394
    }
395
396
397
    /**
398
     * Add security group to a server (addSecurityGroup action)
399
     *
400
     * @param array $options {@see \OpenStack\Compute\v2\Api::postSecurityGroup}
401
     *
402
     * @return SecurityGroup
403
     */
404
    public function addSecurityGroup(array $options) : SecurityGroup
405
    {
406
        $options['id'] = $this->id;
407
408
        $response = $this->execute($this->api->postSecurityGroup(), $options);
409
410
        return $this->model(SecurityGroup::class)->populateFromResponse($response);
411
    }
412
413
    /**
414
     * Add security group to a server (addSecurityGroup action)
415
     *
416
     * @param array $options {@see \OpenStack\Compute\v2\Api::deleteSecurityGroup}
417
     */
418
    public function removeSecurityGroup(array $options)
419
    {
420
        $options['id'] = $this->id;
421
        $this->execute($this->api->deleteSecurityGroup(), $options);
422
    }
423
424
    public function parseMetadata(ResponseInterface $response): array
425
    {
426
        return Utils::jsonDecode($response)['metadata'];
427
    }
428
429
    /**
430
     * Returns Generator for SecurityGroups
431
     *
432
     * @return \Generator
433
     */
434
    public function listSecurityGroups(): \Generator
435
    {
436
        return $this->model(SecurityGroup::class)->enumerate($this->api->getSecurityGroups(), ['id' => $this->id]);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface OpenStack\Common\Resource\ResourceInterface as the method enumerate() does only exist in the following implementations of said interface: OpenStack\BlockStorage\v2\Models\QuotaSet, OpenStack\BlockStorage\v2\Models\Snapshot, OpenStack\BlockStorage\v2\Models\Volume, OpenStack\BlockStorage\v2\Models\VolumeAttachment, OpenStack\BlockStorage\v2\Models\VolumeType, OpenStack\Common\Resource\OperatorResource, OpenStack\Compute\v2\Models\AvailabilityZone, OpenStack\Compute\v2\Models\Flavor, OpenStack\Compute\v2\Models\Host, OpenStack\Compute\v2\Models\Hypervisor, OpenStack\Compute\v2\Models\HypervisorStatistic, OpenStack\Compute\v2\Models\Image, OpenStack\Compute\v2\Models\Keypair, OpenStack\Compute\v2\Models\QuotaSet, OpenStack\Compute\v2\Models\Server, OpenStack\Identity\v2\Models\Catalog, OpenStack\Identity\v2\Models\Endpoint, OpenStack\Identity\v2\Models\Entry, OpenStack\Identity\v2\Models\Tenant, OpenStack\Identity\v2\Models\Token, OpenStack\Identity\v3\Models\Assignment, OpenStack\Identity\v3\Models\Catalog, OpenStack\Identity\v3\Models\Credential, OpenStack\Identity\v3\Models\Domain, OpenStack\Identity\v3\Models\Endpoint, OpenStack\Identity\v3\Models\Group, OpenStack\Identity\v3\Models\Policy, OpenStack\Identity\v3\Models\Project, OpenStack\Identity\v3\Models\Role, OpenStack\Identity\v3\Models\Service, OpenStack\Identity\v3\Models\Token, OpenStack\Identity\v3\Models\User, OpenStack\Images\v2\Models\Image, OpenStack\Images\v2\Models\Member, OpenStack\Networking\v2\...ayer3\Models\FloatingIp, OpenStack\Networking\v2\...ns\Layer3\Models\Router, OpenStack\Networking\v2\...ps\Models\SecurityGroup, OpenStack\Networking\v2\...odels\SecurityGroupRule, OpenStack\Networking\v2\Models\Network, OpenStack\Networking\v2\Models\Port, OpenStack\Networking\v2\Models\Quota, OpenStack\Networking\v2\Models\Subnet, OpenStack\ObjectStore\v1\Models\Account, OpenStack\ObjectStore\v1\Models\Container, OpenStack\ObjectStore\v1\Models\Object.

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...
437
    }
438
439
440
    /**
441
     * Returns Generator for VolumeAttachment
442
     *
443
     * @return \Generator
444
     */
445
    public function listVolumeAttachments(): \Generator
446
    {
447
        return $this->model(VolumeAttachment::class)->enumerate($this->api->getVolumeAttachments(), ['id' => $this->id]);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface OpenStack\Common\Resource\ResourceInterface as the method enumerate() does only exist in the following implementations of said interface: OpenStack\BlockStorage\v2\Models\QuotaSet, OpenStack\BlockStorage\v2\Models\Snapshot, OpenStack\BlockStorage\v2\Models\Volume, OpenStack\BlockStorage\v2\Models\VolumeAttachment, OpenStack\BlockStorage\v2\Models\VolumeType, OpenStack\Common\Resource\OperatorResource, OpenStack\Compute\v2\Models\AvailabilityZone, OpenStack\Compute\v2\Models\Flavor, OpenStack\Compute\v2\Models\Host, OpenStack\Compute\v2\Models\Hypervisor, OpenStack\Compute\v2\Models\HypervisorStatistic, OpenStack\Compute\v2\Models\Image, OpenStack\Compute\v2\Models\Keypair, OpenStack\Compute\v2\Models\QuotaSet, OpenStack\Compute\v2\Models\Server, OpenStack\Identity\v2\Models\Catalog, OpenStack\Identity\v2\Models\Endpoint, OpenStack\Identity\v2\Models\Entry, OpenStack\Identity\v2\Models\Tenant, OpenStack\Identity\v2\Models\Token, OpenStack\Identity\v3\Models\Assignment, OpenStack\Identity\v3\Models\Catalog, OpenStack\Identity\v3\Models\Credential, OpenStack\Identity\v3\Models\Domain, OpenStack\Identity\v3\Models\Endpoint, OpenStack\Identity\v3\Models\Group, OpenStack\Identity\v3\Models\Policy, OpenStack\Identity\v3\Models\Project, OpenStack\Identity\v3\Models\Role, OpenStack\Identity\v3\Models\Service, OpenStack\Identity\v3\Models\Token, OpenStack\Identity\v3\Models\User, OpenStack\Images\v2\Models\Image, OpenStack\Images\v2\Models\Member, OpenStack\Networking\v2\...ayer3\Models\FloatingIp, OpenStack\Networking\v2\...ns\Layer3\Models\Router, OpenStack\Networking\v2\...ps\Models\SecurityGroup, OpenStack\Networking\v2\...odels\SecurityGroupRule, OpenStack\Networking\v2\Models\Network, OpenStack\Networking\v2\Models\Port, OpenStack\Networking\v2\Models\Quota, OpenStack\Networking\v2\Models\Subnet, OpenStack\ObjectStore\v1\Models\Account, OpenStack\ObjectStore\v1\Models\Container, OpenStack\ObjectStore\v1\Models\Object.

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...
448
    }
449
450
    /**
451
     * Attach a volume and returns volume that was attached
452
     *
453
     * @param $volumeId
454
     *
455
     * @return VolumeAttachment
456
     */
457
    public function attachVolume(string $volumeId): VolumeAttachment
458
    {
459
        $response =  $this->execute($this->api->postVolumeAttachments(), ['id' => $this->id, 'volumeId' => $volumeId]);
460
461
        return $this->model(VolumeAttachment::class)->populateFromResponse($response);
462
    }
463
464
    /**
465
     * Detach a volume
466
     *
467
     * @param $attachmentId
468
     *
469
     * @return void
470
     */
471
    public function detachVolume(string $attachmentId)
472
    {
473
        $this->execute($this->api->deleteVolumeAttachments(), ['id' => $this->id, 'attachmentId' => $attachmentId]);
474
    }
475
}
476