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 (#152)
by Chris
01:43
created

Server::addSecurityGroup()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
c 0
b 0
f 0
rs 9.4285
ccs 0
cts 0
cp 0
cc 1
eloc 4
nc 1
nop 1
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\Networking\v2\Models\InterfaceAttachment;
15
use OpenStack\Compute\v2\Enum;
16
use OpenStack\Networking\v2\Extensions\SecurityGroups\Models\SecurityGroup;
17
use Psr\Http\Message\ResponseInterface;
18
19
/**
20
 * @property \OpenStack\Compute\v2\Api $api
21
 */
22
class Server extends OperatorResource implements
23
    Creatable,
24
    Updateable,
25
    Deletable,
26
    Retrievable,
27
    Listable
28
{
29
    use HasWaiterTrait;
30
31
    /** @var string */
32
    public $id;
33
34
    /** @var string */
35
    public $ipv4;
36
37
    /** @var string */
38
    public $ipv6;
39
40
    /** @var array */
41
    public $addresses;
42
43
    /** @var \DateTimeImmutable */
44
    public $created;
45
46
    /** @var \DateTimeImmutable */
47
    public $updated;
48
49
    /** @var Flavor */
50
    public $flavor;
51
52
    /** @var string */
53
    public $hostId;
54
55
    /** @var string */
56
    public $hypervisorHostname;
57
58
    /** @var Image */
59
    public $image;
60
61
    /** @var array */
62
    public $links;
63
64
    /** @var array */
65
    public $metadata;
66
67
    /** @var string */
68
    public $name;
69
70
    /** @var string */
71
    public $progress;
72
73
    /** @var string */
74
    public $status;
75
76
    /** @var string */
77
    public $tenantId;
78
79
    /** @var string */
80
    public $userId;
81
82
    /** @var string */
83
    public $adminPass;
84
85
    /** @var string */
86
    public $taskState;
87
88
    /** @var string */
89
    public $powerState;
90
91
    /** @var string */
92
    public $vmState;
93
94
    protected $resourceKey = 'server';
95
    protected $resourcesKey = 'servers';
96
    protected $markerKey = 'id';
97
98
    protected $aliases = [
99
        'block_device_mapping_v2'             => 'blockDeviceMapping',
100
        'accessIPv4'                          => 'ipv4',
101 2
        'accessIPv6'                          => 'ipv6',
102
        'tenant_id'                           => 'tenantId',
103 2
        'user_id'                             => 'userId',
104 2
        'security_groups'                     => 'securityGroups',
105
        'OS-EXT-STS:task_state'               => 'taskState',
106
        'OS-EXT-STS:power_state'              => 'powerState',
107
        'OS-EXT-STS:vm_state'                 => 'vmState',
108
        'OS-EXT-SRV-ATTR:hypervisor_hostname' => 'hypervisorHostname',
109
    ];
110 1
111
    /**
112 1
     * {@inheritDoc}
113
     *
114 1
     * @param array $userOptions {@see \OpenStack\Compute\v2\Api::postServer}
115
     */
116
    public function create(array $userOptions): Creatable
117
    {
118
        if (!isset($userOptions['imageId']) && !isset($userOptions['blockDeviceMapping'][0]['uuid'])) {
119
            throw new \RuntimeException('imageId or blockDeviceMapping.uuid must be set.');
120 1
        }
121
122 1
        $response = $this->execute($this->api->postServer(), $userOptions);
123 1
        return $this->populateFromResponse($response);
124
    }
125
126
    /**
127
     * {@inheritDoc}
128 1
     */
129
    public function update()
130 1
    {
131
        $response = $this->execute($this->api->putServer(), $this->getAttrs(['id', 'name', 'ipv4', 'ipv6']));
132 1
        $this->populateFromResponse($response);
133
    }
134
135
    /**
136
     * {@inheritDoc}
137
     */
138
    public function delete()
139
    {
140 1
        $this->execute($this->api->deleteServer(), $this->getAttrs(['id']));
141
    }
142 1
143 1
    /**
144
     * {@inheritDoc}
145 1
     */
146 1
    public function retrieve()
147
    {
148
        $response = $this->execute($this->api->getServer(), $this->getAttrs(['id']));
149
        $this->populateFromResponse($response);
150
    }
151
152
    /**
153 2
     * Changes the root password for a server.
154
     *
155 2
     * @param string $newPassword The new root password
156 1
     */
157
    public function changePassword(string $newPassword)
158
    {
159 1
        $this->execute($this->api->changeServerPassword(), [
160 1
            'id'       => $this->id,
161 1
            'password' => $newPassword,
162 1
        ]);
163 1
    }
164
165
    /**
166
     * Reboots the server.
167
     *
168
     * @param string $type The type of reboot that will be performed. Either SOFT or HARD is supported.
169
     */
170 1
    public function reboot(string $type = Enum::REBOOT_SOFT)
171
    {
172 1
        if (!in_array($type, ['SOFT', 'HARD'])) {
173 1
            throw new \RuntimeException('Reboot type must either be SOFT or HARD');
174
        }
175 1
176 1
        $this->execute($this->api->rebootServer(), [
177
            'id'   => $this->id,
178
            'type' => $type,
179
        ]);
180
    }
181
182
    /**
183
     * Starts server
184 1
     */
185
    public function start()
186 1
    {
187 1
        $this->execute($this->api->startServer(), [
188 1
            'id' => $this->id,
189 1
            'os-start' => null
190
        ]);
191 1
    }
192 1
193
    /**
194
     * Stops server
195
     */
196
    public function stop()
197 1
    {
198
        $this->execute($this->api->stopServer(), [
199 1
            'id' => $this->id,
200 1
            'os-stop' => null
201
        ]);
202
    }
203
204
    /**
205 1
     * Shelves server
206
     */
207 1
    public function shelve()
208 1
    {
209
        $this->execute($this->api->shelveServer(), [
210
            'id' => $this->id,
211
            'shelve' => null
212
        ]);
213
    }
214
215 1
    /*
216
     * Suspend server
217 1
     */
218 1
    public function suspend()
219 1
    {
220
        $this->execute($this->api->suspendServer(), [
221
            'id' => $this->id,
222
            'suspend' => null
223
        ]);
224
    }
225
226
    /**
227
     * Shelf-offloads server
228 2
     */
229
    public function shelveOffload()
230 2
    {
231
        $this->execute($this->api->shelveOffloadServer(), [
232 2
            'id' => $this->id,
233 2
            'shelveOffload' => null
234 2
        ]);
235
    }
236
237
    /**
238
     * Unshelves server
239
     */
240
    public function unshelve()
241
    {
242 1
        $this->execute($this->api->unshelveServer(), [
243
            'id' => $this->id,
244 1
            'unshelve' => null
245 1
        ]);
246
    }
247
248
    /*
249
     * Resume server
250
     */
251
    public function resume()
252
    {
253
        $this->execute($this->api->resumeServer(), [
254
            'id' => $this->id,
255
            'resume' => null
256 1
        ]);
257
    }
258 1
259 1
    /**
260
     * Locks server
261
     */
262
    public function lock()
263
    {
264
        $this->execute($this->api->lockServer(), [
265
            'id' => $this->id,
266
            'lock' => null
267
        ]);
268
    }
269
270
    /**
271 1
     * Unlocks server
272
     */
273 1
    public function unlock()
274 1
    {
275
        $this->execute($this->api->unlockServer(), [
276
            'id' => $this->id,
277
            'unlock' => null
278
        ]);
279
    }
280
281
    /**
282
     * Rebuilds the server.
283
     *
284 1
     * @param array $options {@see \OpenStack\Compute\v2\Api::rebuildServer}
285
     */
286 1
    public function rebuild(array $options)
287 1
    {
288
        $options['id'] = $this->id;
289
        $response = $this->execute($this->api->rebuildServer(), $options);
290
291
        $this->populateFromResponse($response);
292
    }
293
294
    /**
295 1
     * Resizes the server to a new flavor. Once this operation is complete and server has transitioned
296
     * to an active state, you will either need to call {@see confirmResize()} or {@see revertResize()}.
297 1
     *
298 1
     * @param string $flavorId The UUID of the new flavor your server will be based on.
299
     */
300
    public function resize(string $flavorId)
301
    {
302
        $response = $this->execute($this->api->resizeServer(), [
303
            'id'       => $this->id,
304
            'flavorId' => $flavorId,
305
        ]);
306
307
        $this->populateFromResponse($response);
308
    }
309
310
    /**
311
     * Confirms a previous resize operation.
312
     */
313
    public function confirmResize()
314
    {
315
        $this->execute($this->api->confirmServerResize(), ['confirmResize' => null, 'id' => $this->id]);
316
    }
317
318
    /**
319
     * Reverts a previous resize operation.
320
     */
321
    public function revertResize()
322
    {
323
        $this->execute($this->api->revertServerResize(), ['revertResize' => null, 'id' => $this->id]);
324
    }
325
326
    /**
327
     * Gets a VNC console for a server.
328
     *
329
     * @param  string $type The type of VNC console: novnc|xvpvnc.
330
     *                      Defaults to novnc.
331
     *
332
     * @return array
333
     */
334
    public function getVncConsole($type = Enum::CONSOLE_NOVNC): array
335
    {
336
        $response = $this->execute($this->api->getVncConsole(), ['id' => $this->id, 'type' => $type]);
337
        return Utils::jsonDecode($response)['console'];
338
    }
339
340
    /**
341
     * Gets a RDP console for a server.
342
     *
343
     * @param  string $type The type of VNC console: rdp-html5 (default).
344
     *
345
     * @return array
346
     */
347
    public function getRDPConsole($type = Enum::CONSOLE_RDP_HTML5): array
348
    {
349
        $response = $this->execute($this->api->getRDPConsole(), ['id' => $this->id, 'type' => $type]);
350
        return Utils::jsonDecode($response)['console'];
351
    }
352
353
    /**
354
     * Gets a Spice console for a server.
355
     *
356
     * @param  string $type The type of VNC console: spice-html5.
357
     *
358
     * @return array
359
     */
360
    public function getSpiceConsole($type = Enum::CONSOLE_SPICE_HTML5): array
361
    {
362
        $response = $this->execute($this->api->getSpiceConsole(), ['id' => $this->id, 'type' => $type]);
363
        return Utils::jsonDecode($response)['console'];
364
    }
365
366
    /**
367
     * Gets a serial console for a server.
368
     *
369
     * @param  string $type The type of VNC console: serial.
370
     *
371
     * @return array
372
     */
373
    public function getSerialConsole($type = Enum::CONSOLE_SERIAL): array
374
    {
375
        $response = $this->execute($this->api->getSerialConsole(), ['id' => $this->id, 'type' => $type]);
376
        return Utils::jsonDecode($response)['console'];
377
    }
378
379
    /**
380
     * Get the console log.
381
     *
382
     * @param int $length Number of lines of console log to grab.
383
     *
384
     * @return string - the console log output
385
     */
386
    public function getConsoleLog(int $length = 50): string {
387
        $response = $this->execute($this->api->getConsoleLog(), ['id' => $this->id, 'length' => $length]);
388
        return Utils::jsonDecode($response)['output'];
389
    }
390
391
    /**
392
     * Creates an image for the current server.
393
     *
394
     * @param array $options {@see \OpenStack\Compute\v2\Api::createServerImage}
395
     */
396
    public function createImage(array $options)
397
    {
398
        $options['id'] = $this->id;
399
        $this->execute($this->api->createServerImage(), $options);
400
    }
401
402
    /**
403
     * Iterates over all the IP addresses for this server.
404
     *
405
     * @param array $options {@see \OpenStack\Compute\v2\Api::getAddressesByNetwork}
406
     *
407
     * @return array An array containing to two keys: "public" and "private"
408
     */
409
    public function listAddresses(array $options = []): array
410
    {
411
        $options['id'] = $this->id;
412
413
        $data = (isset($options['networkLabel'])) ? $this->api->getAddressesByNetwork() : $this->api->getAddresses();
414
        $response = $this->execute($data, $options);
415
        return Utils::jsonDecode($response)['addresses'];
416
    }
417
418
    /**
419
     * Returns Generator for InterfaceAttachment
420
     *
421
     * @return \Generator
422
     */
423
    public function listInterfaceAttachments(array $options = []): \Generator
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
424
    {
425
        return $this->model(InterfaceAttachment::class)->enumerate($this->api->getInterfaceAttachments(), ['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\InstanceAction, 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\Metric\v1\Gnocchi\Models\Metric, OpenStack\Metric\v1\Gnocchi\Models\Resource, OpenStack\Metric\v1\Gnocchi\Models\ResourceType, 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\InterfaceAttachment, OpenStack\Networking\v2\Models\LoadBalancer, OpenStack\Networking\v2\...adBalancerHealthMonitor, OpenStack\Networking\v2\...ls\LoadBalancerListener, OpenStack\Networking\v2\Models\LoadBalancerMember, OpenStack\Networking\v2\Models\LoadBalancerPool, OpenStack\Networking\v2\Models\LoadBalancerStat, OpenStack\Networking\v2\Models\LoadBalancerStatus, OpenStack\Networking\v2\Models\Network, OpenStack\Networking\v2\...s\NetworkIpAvailability, 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...
426
    }
427
428
    /**
429
     * Retrieves metadata from the API.
430
     *
431
     * @return array
432
     */
433
    public function getMetadata(): array
434
    {
435
        $response = $this->execute($this->api->getServerMetadata(), ['id' => $this->id]);
436
        return $this->parseMetadata($response);
437
    }
438
439
    /**
440
     * Resets all the metadata for this server with the values provided. All existing metadata keys
441
     * will either be replaced or removed.
442
     *
443
     * @param array $metadata {@see \OpenStack\Compute\v2\Api::putServerMetadata}
444
     */
445
    public function resetMetadata(array $metadata)
446
    {
447
        $response = $this->execute($this->api->putServerMetadata(), ['id' => $this->id, 'metadata' => $metadata]);
448
        $this->metadata = $this->parseMetadata($response);
449
    }
450
451
    /**
452
     * Merges the existing metadata for the server with the values provided. Any existing keys
453
     * referenced in the user options will be replaced with the user's new values. All other
454
     * existing keys will remain unaffected.
455
     *
456
     * @param array $metadata {@see \OpenStack\Compute\v2\Api::postServerMetadata}
457
     *
458
     * @return array
459
     */
460
    public function mergeMetadata(array $metadata)
461
    {
462
        $response = $this->execute($this->api->postServerMetadata(), ['id' => $this->id, 'metadata' => $metadata]);
463
        $this->metadata = $this->parseMetadata($response);
464
    }
465
466
    /**
467
     * Retrieve the value for a specific metadata key.
468
     *
469
     * @param string $key {@see \OpenStack\Compute\v2\Api::getServerMetadataKey}
470
     *
471
     * @return mixed
472
     */
473 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...
474
    {
475
        $response = $this->execute($this->api->getServerMetadataKey(), ['id' => $this->id, 'key' => $key]);
476
        $value = $this->parseMetadata($response)[$key];
477
        $this->metadata[$key] = $value;
478
        return $value;
479
    }
480
481
    /**
482
     * Remove a specific metadata key.
483
     *
484
     * @param string $key {@see \OpenStack\Compute\v2\Api::deleteServerMetadataKey}
485
     */
486 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...
487
    {
488
        if (isset($this->metadata[$key])) {
489
            unset($this->metadata[$key]);
490
        }
491
492
        $this->execute($this->api->deleteServerMetadataKey(), ['id' => $this->id, 'key' => $key]);
493
    }
494
495
496
    /**
497
     * Add security group to a server (addSecurityGroup action)
498
     *
499
     * @param array $options {@see \OpenStack\Compute\v2\Api::postSecurityGroup}
500
     *
501
     * @return SecurityGroup
502
     */
503
    public function addSecurityGroup(array $options) : SecurityGroup
504
    {
505
        $options['id'] = $this->id;
506
507
        $response = $this->execute($this->api->postSecurityGroup(), $options);
508
509
        return $this->model(SecurityGroup::class)->populateFromResponse($response);
510
    }
511
512
    /**
513
     * Add security group to a server (addSecurityGroup action)
514
     *
515
     * @param array $options {@see \OpenStack\Compute\v2\Api::deleteSecurityGroup}
516
     */
517
    public function removeSecurityGroup(array $options)
518
    {
519
        $options['id'] = $this->id;
520
        $this->execute($this->api->deleteSecurityGroup(), $options);
521
    }
522
523
    public function parseMetadata(ResponseInterface $response): array
524
    {
525
        return Utils::jsonDecode($response)['metadata'];
526
    }
527
528
    /**
529
     * Returns Generator for SecurityGroups
530
     *
531
     * @return \Generator
532
     */
533
    public function listSecurityGroups(): \Generator
534
    {
535
        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\InstanceAction, 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\Metric\v1\Gnocchi\Models\Metric, OpenStack\Metric\v1\Gnocchi\Models\Resource, OpenStack\Metric\v1\Gnocchi\Models\ResourceType, 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\InterfaceAttachment, OpenStack\Networking\v2\Models\LoadBalancer, OpenStack\Networking\v2\...adBalancerHealthMonitor, OpenStack\Networking\v2\...ls\LoadBalancerListener, OpenStack\Networking\v2\Models\LoadBalancerMember, OpenStack\Networking\v2\Models\LoadBalancerPool, OpenStack\Networking\v2\Models\LoadBalancerStat, OpenStack\Networking\v2\Models\LoadBalancerStatus, OpenStack\Networking\v2\Models\Network, OpenStack\Networking\v2\...s\NetworkIpAvailability, 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...
536
    }
537
538
539
    /**
540
     * Returns Generator for VolumeAttachment
541
     *
542
     * @return \Generator
543
     */
544
    public function listVolumeAttachments(): \Generator
545
    {
546
        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\InstanceAction, 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\Metric\v1\Gnocchi\Models\Metric, OpenStack\Metric\v1\Gnocchi\Models\Resource, OpenStack\Metric\v1\Gnocchi\Models\ResourceType, 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\InterfaceAttachment, OpenStack\Networking\v2\Models\LoadBalancer, OpenStack\Networking\v2\...adBalancerHealthMonitor, OpenStack\Networking\v2\...ls\LoadBalancerListener, OpenStack\Networking\v2\Models\LoadBalancerMember, OpenStack\Networking\v2\Models\LoadBalancerPool, OpenStack\Networking\v2\Models\LoadBalancerStat, OpenStack\Networking\v2\Models\LoadBalancerStatus, OpenStack\Networking\v2\Models\Network, OpenStack\Networking\v2\...s\NetworkIpAvailability, 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...
547
    }
548
549
    /**
550
     * Attach a volume and returns volume that was attached
551
     *
552
     * @param $volumeId
553
     *
554
     * @return VolumeAttachment
555
     */
556
    public function attachVolume(string $volumeId): VolumeAttachment
557
    {
558
        $response =  $this->execute($this->api->postVolumeAttachments(), ['id' => $this->id, 'volumeId' => $volumeId]);
559
560
        return $this->model(VolumeAttachment::class)->populateFromResponse($response);
561
    }
562
563
    /**
564
     * Detach a volume
565
     *
566
     * @param $attachmentId
567
     *
568
     * @return void
569
     */
570
    public function detachVolume(string $attachmentId)
571
    {
572
        $this->execute($this->api->deleteVolumeAttachments(), ['id' => $this->id, 'attachmentId' => $attachmentId]);
573
    }
574
575
    /**
576
     * Get a Generator for the instance actions
577
     *
578
     * @return \Generator
579
     */
580
    public function listInstanceActions(): \Generator
581
    {
582
        return $this->model(InstanceAction::class)->enumerate($this->api->getInstanceActions(), ['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\InstanceAction, 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\Metric\v1\Gnocchi\Models\Metric, OpenStack\Metric\v1\Gnocchi\Models\Resource, OpenStack\Metric\v1\Gnocchi\Models\ResourceType, 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\InterfaceAttachment, OpenStack\Networking\v2\Models\LoadBalancer, OpenStack\Networking\v2\...adBalancerHealthMonitor, OpenStack\Networking\v2\...ls\LoadBalancerListener, OpenStack\Networking\v2\Models\LoadBalancerMember, OpenStack\Networking\v2\Models\LoadBalancerPool, OpenStack\Networking\v2\Models\LoadBalancerStat, OpenStack\Networking\v2\Models\LoadBalancerStatus, OpenStack\Networking\v2\Models\Network, OpenStack\Networking\v2\...s\NetworkIpAvailability, 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...
583
    }
584
585
    /**
586
     * Get a specific instance action
587
     *
588
     * @string The request ID of the instance action
589
     * @return InstanceAction
590
     */
591
    public function getInstanceAction(string $requestId): InstanceAction
592
    {
593
      $response = $this->execute($this->api->getInstanceAction(), ['id' => $this->id, 'requestId' => $requestId]);
594
595
      return $this->model(InstanceAction::class)->populateFromResponse($response);
596
    }
597
}
598