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 (#146)
by Casper
02:59 queued 51s
created

Server::deleteMetadataItem()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 8
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 8
loc 8
ccs 0
cts 0
cp 0
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
crap 6
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
    protected $resourceKey = 'server';
89
    protected $resourcesKey = 'servers';
90
    protected $markerKey = 'id';
91
92
    protected $aliases = [
93
        'block_device_mapping_v2'             => 'blockDeviceMapping',
94
        'accessIPv4'                          => 'ipv4',
95
        'accessIPv6'                          => 'ipv6',
96
        'tenant_id'                           => 'tenantId',
97
        'user_id'                             => 'userId',
98
        'security_groups'                     => 'securityGroups',
99
        'OS-EXT-STS:task_state'               => 'taskState',
100
        'OS-EXT-SRV-ATTR:hypervisor_hostname' => 'hypervisorHostname',
101 2
    ];
102
103 2
    /**
104 2
     * {@inheritDoc}
105
     *
106
     * @param array $userOptions {@see \OpenStack\Compute\v2\Api::postServer}
107
     */
108
    public function create(array $userOptions): Creatable
109
    {
110 1
        if (!isset($userOptions['imageId']) && !isset($userOptions['blockDeviceMapping'][0]['uuid'])) {
111
            throw new \RuntimeException('imageId or blockDeviceMapping.uuid must be set.');
112 1
        }
113
114 1
        $response = $this->execute($this->api->postServer(), $userOptions);
115
        return $this->populateFromResponse($response);
116
    }
117
118
    /**
119
     * {@inheritDoc}
120 1
     */
121
    public function update()
122 1
    {
123 1
        $response = $this->execute($this->api->putServer(), $this->getAttrs(['id', 'name', 'ipv4', 'ipv6']));
124
        $this->populateFromResponse($response);
125
    }
126
127
    /**
128 1
     * {@inheritDoc}
129
     */
130 1
    public function delete()
131
    {
132 1
        $this->execute($this->api->deleteServer(), $this->getAttrs(['id']));
133
    }
134
135
    /**
136
     * {@inheritDoc}
137
     */
138
    public function retrieve()
139
    {
140 1
        $response = $this->execute($this->api->getServer(), $this->getAttrs(['id']));
141
        $this->populateFromResponse($response);
142 1
    }
143 1
144
    /**
145 1
     * Changes the root password for a server.
146 1
     *
147
     * @param string $newPassword The new root password
148
     */
149
    public function changePassword(string $newPassword)
150
    {
151
        $this->execute($this->api->changeServerPassword(), [
152
            'id'       => $this->id,
153 2
            'password' => $newPassword,
154
        ]);
155 2
    }
156 1
157
    /**
158
     * Reboots the server.
159 1
     *
160 1
     * @param string $type The type of reboot that will be performed. Either SOFT or HARD is supported.
161 1
     */
162 1
    public function reboot(string $type = Enum::REBOOT_SOFT)
163 1
    {
164
        if (!in_array($type, ['SOFT', 'HARD'])) {
165
            throw new \RuntimeException('Reboot type must either be SOFT or HARD');
166
        }
167
168
        $this->execute($this->api->rebootServer(), [
169
            'id'   => $this->id,
170 1
            'type' => $type,
171
        ]);
172 1
    }
173 1
174
    /**
175 1
     * Starts server
176 1
     */
177
    public function start()
178
    {
179
        $this->execute($this->api->startServer(), [
180
            'id' => $this->id,
181
            'os-start' => null
182
        ]);
183
    }
184 1
185
    /**
186 1
     * Stops server
187 1
     */
188 1
    public function stop()
189 1
    {
190
        $this->execute($this->api->stopServer(), [
191 1
            'id' => $this->id,
192 1
            'os-stop' => null
193
        ]);
194
    }
195
196
    /**
197 1
     * Rebuilds the server.
198
     *
199 1
     * @param array $options {@see \OpenStack\Compute\v2\Api::rebuildServer}
200 1
     */
201
    public function rebuild(array $options)
202
    {
203
        $options['id'] = $this->id;
204
        $response = $this->execute($this->api->rebuildServer(), $options);
205 1
206
        $this->populateFromResponse($response);
207 1
    }
208 1
209
    /**
210
     * Resizes the server to a new flavor. Once this operation is complete and server has transitioned
211
     * to an active state, you will either need to call {@see confirmResize()} or {@see revertResize()}.
212
     *
213
     * @param string $flavorId The UUID of the new flavor your server will be based on.
214
     */
215 1
    public function resize(string $flavorId)
216
    {
217 1
        $response = $this->execute($this->api->resizeServer(), [
218 1
            'id'       => $this->id,
219 1
            'flavorId' => $flavorId,
220
        ]);
221
222
        $this->populateFromResponse($response);
223
    }
224
225
    /**
226
     * Confirms a previous resize operation.
227
     */
228 2
    public function confirmResize()
229
    {
230 2
        $this->execute($this->api->confirmServerResize(), ['confirmResize' => null, 'id' => $this->id]);
231
    }
232 2
233 2
    /**
234 2
     * Reverts a previous resize operation.
235
     */
236
    public function revertResize()
237
    {
238
        $this->execute($this->api->revertServerResize(), ['revertResize' => null, 'id' => $this->id]);
239
    }
240
241
    /**
242 1
     * Gets a VNC console for a server.
243
     *
244 1
     * @param  string $type The type of VNC console: novnc|xvpvnc.
245 1
     *                      Defaults to novnc.
246
     *
247
     * @return array
248
     */
249
    public function getVncConsole($type = Enum::CONSOLE_NOVNC): array
250
    {
251
        $response = $this->execute($this->api->getVncConsole(), ['id' => $this->id, 'type' => $type]);
252
        return Utils::jsonDecode($response)['console'];
253
    }
254
255
    /**
256 1
     * Gets a RDP console for a server.
257
     *
258 1
     * @param  string $type The type of VNC console: rdp-html5 (default).
259 1
     *
260
     * @return array
261
     */
262
    public function getRDPConsole($type = Enum::CONSOLE_RDP_HTML5): array
263
    {
264
        $response = $this->execute($this->api->getRDPConsole(), ['id' => $this->id, 'type' => $type]);
265
        return Utils::jsonDecode($response)['console'];
266
    }
267
268
    /**
269
     * Gets a Spice console for a server.
270
     *
271 1
     * @param  string $type The type of VNC console: spice-html5.
272
     *
273 1
     * @return array
274 1
     */
275
    public function getSpiceConsole($type = Enum::CONSOLE_SPICE_HTML5): array
276
    {
277
        $response = $this->execute($this->api->getSpiceConsole(), ['id' => $this->id, 'type' => $type]);
278
        return Utils::jsonDecode($response)['console'];
279
    }
280
281
    /**
282
     * Gets a serial console for a server.
283
     *
284 1
     * @param  string $type The type of VNC console: serial.
285
     *
286 1
     * @return array
287 1
     */
288
    public function getSerialConsole($type = Enum::CONSOLE_SERIAL): array
289
    {
290
        $response = $this->execute($this->api->getSerialConsole(), ['id' => $this->id, 'type' => $type]);
291
        return Utils::jsonDecode($response)['console'];
292
    }
293
294
    /**
295 1
     * Creates an image for the current server.
296
     *
297 1
     * @param array $options {@see \OpenStack\Compute\v2\Api::createServerImage}
298 1
     */
299
    public function createImage(array $options)
300
    {
301
        $options['id'] = $this->id;
302
        $this->execute($this->api->createServerImage(), $options);
303
    }
304
305
    /**
306
     * Iterates over all the IP addresses for this server.
307
     *
308
     * @param array $options {@see \OpenStack\Compute\v2\Api::getAddressesByNetwork}
309
     *
310
     * @return array An array containing to two keys: "public" and "private"
311
     */
312
    public function listAddresses(array $options = []): array
313
    {
314
        $options['id'] = $this->id;
315
316
        $data = (isset($options['networkLabel'])) ? $this->api->getAddressesByNetwork() : $this->api->getAddresses();
317
        $response = $this->execute($data, $options);
318
        return Utils::jsonDecode($response)['addresses'];
319
    }
320
321
    /**
322
     * Returns Generator for InterfaceAttachment
323
     *
324
     * @return \Generator
325
     */
326
    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...
327
    {
328
        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\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\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...
329
    }
330
331
    /**
332
     * Gets an interface attachment.
333
     *
334
     * @param string $portId The unique ID of the port.
335
     * @return InterfaceAttachment
336
     */
337 View Code Duplication
    public function getInterfaceAttachment($portId): InterfaceAttachment
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...
338
    {
339
        $response = $this->execute($this->api->getInterfaceAttachment(), [
340
            'id'     => $this->id,
341
            'portId' => $portId
342
        ]);
343
344
        return $this->model(InterfaceAttachment::class)->populateFromResponse($response);
345
    }
346
347
    /**
348
     * Creates an interface attachment.
349
     *
350
     * @param array $userOptions {@see \OpenStack\Compute\v2\Api::postInterfaceAttachment}
351
     * @return InterfaceAttachment
352
     */
353
    public function createInterfaceAttachment(array $userOptions): InterfaceAttachment
354
    {
355
        if (!isset($userOptions['networkId']) && !isset($userOptions['portId'])) {
356
            throw new \RuntimeException('networkId or portId must be set.');
357
        }
358
359
        $response = $this->execute($this->api->postInterfaceAttachment(), array_merge($userOptions, ['id' => $this->id]));
360
        return $this->model(InterfaceAttachment::class)->populateFromResponse($response);
361
    }
362
363
    /**
364
     * Detaches an interface attachment.
365
     *
366
     * @param string $portId
367
     */
368
    public function detachInterface(string $portId)
369
    {
370
        $this->execute($this->api->deleteInterfaceAttachment(), [
371
            'id' => $this->id,
372
            'portId' => $portId,
373
        ]);
374
    }
375
376
    /**
377
     * Retrieves metadata from the API.
378
     *
379
     * @return array
380
     */
381
    public function getMetadata(): array
382
    {
383
        $response = $this->execute($this->api->getServerMetadata(), ['id' => $this->id]);
384
        return $this->parseMetadata($response);
385
    }
386
387
    /**
388
     * Resets all the metadata for this server with the values provided. All existing metadata keys
389
     * will either be replaced or removed.
390
     *
391
     * @param array $metadata {@see \OpenStack\Compute\v2\Api::putServerMetadata}
392
     */
393
    public function resetMetadata(array $metadata)
394
    {
395
        $response = $this->execute($this->api->putServerMetadata(), ['id' => $this->id, 'metadata' => $metadata]);
396
        $this->metadata = $this->parseMetadata($response);
397
    }
398
399
    /**
400
     * Merges the existing metadata for the server with the values provided. Any existing keys
401
     * referenced in the user options will be replaced with the user's new values. All other
402
     * existing keys will remain unaffected.
403
     *
404
     * @param array $metadata {@see \OpenStack\Compute\v2\Api::postServerMetadata}
405
     *
406
     * @return array
407
     */
408
    public function mergeMetadata(array $metadata)
409
    {
410
        $response = $this->execute($this->api->postServerMetadata(), ['id' => $this->id, 'metadata' => $metadata]);
411
        $this->metadata = $this->parseMetadata($response);
412
    }
413
414
    /**
415
     * Retrieve the value for a specific metadata key.
416
     *
417
     * @param string $key {@see \OpenStack\Compute\v2\Api::getServerMetadataKey}
418
     *
419
     * @return mixed
420
     */
421 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...
422
    {
423
        $response = $this->execute($this->api->getServerMetadataKey(), ['id' => $this->id, 'key' => $key]);
424
        $value = $this->parseMetadata($response)[$key];
425
        $this->metadata[$key] = $value;
426
        return $value;
427
    }
428
429
    /**
430
     * Remove a specific metadata key.
431
     *
432
     * @param string $key {@see \OpenStack\Compute\v2\Api::deleteServerMetadataKey}
433
     */
434 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...
435
    {
436
        if (isset($this->metadata[$key])) {
437
            unset($this->metadata[$key]);
438
        }
439
440
        $this->execute($this->api->deleteServerMetadataKey(), ['id' => $this->id, 'key' => $key]);
441
    }
442
443
444
    /**
445
     * Add security group to a server (addSecurityGroup action)
446
     *
447
     * @param array $options {@see \OpenStack\Compute\v2\Api::postSecurityGroup}
448
     *
449
     * @return SecurityGroup
450
     */
451 View Code Duplication
    public function addSecurityGroup(array $options) : SecurityGroup
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...
452
    {
453
        $options['id'] = $this->id;
454
455
        $response = $this->execute($this->api->postSecurityGroup(), $options);
456
457
        return $this->model(SecurityGroup::class)->populateFromResponse($response);
458
    }
459
460
    /**
461
     * Add security group to a server (addSecurityGroup action)
462
     *
463
     * @param array $options {@see \OpenStack\Compute\v2\Api::deleteSecurityGroup}
464
     */
465
    public function removeSecurityGroup(array $options)
466
    {
467
        $options['id'] = $this->id;
468
        $this->execute($this->api->deleteSecurityGroup(), $options);
469
    }
470
471
    public function parseMetadata(ResponseInterface $response): array
472
    {
473
        return Utils::jsonDecode($response)['metadata'];
474
    }
475
476
    /**
477
     * Returns Generator for SecurityGroups
478
     *
479
     * @return \Generator
480
     */
481
    public function listSecurityGroups(): \Generator
482
    {
483
        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\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\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...
484
    }
485
486
487
    /**
488
     * Returns Generator for VolumeAttachment
489
     *
490
     * @return \Generator
491
     */
492
    public function listVolumeAttachments(): \Generator
493
    {
494
        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\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\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...
495
    }
496
497
    /**
498
     * Attach a volume and returns volume that was attached
499
     *
500
     * @param $volumeId
501
     *
502
     * @return VolumeAttachment
503
     */
504
    public function attachVolume(string $volumeId): VolumeAttachment
505
    {
506
        $response =  $this->execute($this->api->postVolumeAttachments(), ['id' => $this->id, 'volumeId' => $volumeId]);
507
508
        return $this->model(VolumeAttachment::class)->populateFromResponse($response);
509
    }
510
511
    /**
512
     * Detach a volume
513
     *
514
     * @param $attachmentId
515
     *
516
     * @return void
517
     */
518
    public function detachVolume(string $attachmentId)
519
    {
520
        $this->execute($this->api->deleteVolumeAttachments(), ['id' => $this->id, 'attachmentId' => $attachmentId]);
521
    }
522
}
523