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 (#159)
by Roman
01:49
created

Server::getAlias()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

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