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.

Image::uploadData()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.4285
ccs 3
cts 3
cp 1
cc 1
eloc 5
nc 1
nop 1
crap 1
1
<?php declare(strict_types=1);
2
3
namespace OpenStack\Images\v2\Models;
4
5
use function GuzzleHttp\Psr7\uri_for;
6
use OpenStack\Common\JsonSchema\Schema;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, OpenStack\Images\v2\Models\Schema.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
use OpenStack\Common\Resource\Alias;
8
use OpenStack\Common\Resource\OperatorResource;
9
use OpenStack\Common\Resource\Creatable;
10
use OpenStack\Common\Resource\Deletable;
11
use OpenStack\Common\Resource\Listable;
12
use OpenStack\Common\Resource\Retrievable;
13
use OpenStack\Common\Transport\Utils;
14
use OpenStack\Images\v2\JsonPatch;
15
use Psr\Http\Message\StreamInterface;
16
17
/**
18
 * @property \OpenStack\Images\v2\Api $api
19
 */
20
class Image extends OperatorResource implements Creatable, Listable, Retrievable, Deletable
21
{
22
    /** @var string */
23
    public $status;
24
25
    /** @var string */
26
    public $name;
27
28
    /** @var array */
29
    public $tags;
30
31
    /** @var string */
32
    public $containerFormat;
33
34
    /** @var \DateTimeImmutable */
35
    public $createdAt;
36
37
    /** @var string */
38
    public $diskFormat;
39
40
    /** @var \DateTimeImmutable */
41
    public $updatedAt;
42
43
    /** @var string */
44
    public $visibility;
45
46
    /** @var int */
47
    public $minDisk;
48
49
    /** @var bool */
50
    public $protected;
51
52
    /** @var string */
53
    public $id;
54
55
    /** @var \GuzzleHttp\Psr7\Uri */
56
    public $fileUri;
57
58
    /** @var string */
59
    public $checksum;
60
61
    /** @var string */
62
    public $ownerId;
63
64
    /** @var int */
65
    public $size;
66
67
    /** @var int */
68
    public $minRam;
69
70
    /** @var \GuzzleHttp\Psr7\Uri */
71
    public $schemaUri;
72
73
    /** @var int */
74
    public $virtualSize;
75
76
    private $jsonSchema;
77
78
    protected $aliases = [
79
        'container_format' => 'containerFormat',
80
        'disk_format'      => 'diskFormat',
81
        'min_disk'         => 'minDisk',
82
        'owner'            => 'ownerId',
83
        'min_ram'          => 'minRam',
84
        'virtual_size'     => 'virtualSize',
85
    ];
86
87 7
    /**
88
     * @inheritdoc
89 6
     */
90 View Code Duplication
    protected function getAliases(): array
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...
91 6
    {
92
        return parent::getAliases() + [
93 6
            'created_at' => new Alias('createdAt', \DateTimeImmutable::class),
94 5
            'updated_at' => new Alias('updatedAt', \DateTimeImmutable::class),
95 5
            'fileUri'    => new Alias('fileUri', \GuzzleHttp\Psr7\Uri::class),
96
            'schemaUri'  => new Alias('schemaUri', \GuzzleHttp\Psr7\Uri::class)
97 6
        ];
98 5
    }
99 5
100 7
    public function populateFromArray(array $data): self
101
    {
102 1
        parent::populateFromArray($data);
103
104 1
        $baseUri = $this->getHttpBaseUrl();
105 1
106
        if (isset($data['file'])) {
107
            $this->fileUri = Utils::appendPath($baseUri, $data['file']);
108 3
        }
109
110 3
        if (isset($data['schema'])) {
111 3
            $this->schemaUri = Utils::appendPath($baseUri, $data['schema']);
112
        }
113
114 2
        return $this;
115
    }
116 2
117 2
    public function create(array $data): Creatable
118 2
    {
119 2
        $response = $this->execute($this->api->postImages(), $data);
120
        return $this->populateFromResponse($response);
121 2
    }
122
123
    public function retrieve()
124 2
    {
125
        $response = $this->executeWithState($this->api->getImage());
126
        $this->populateFromResponse($response);
127 2
    }
128
129 2
    private function getSchema(): Schema
130 2
    {
131
        if (null === $this->jsonSchema) {
132
            $response = $this->execute($this->api->getImageSchema());
133 2
            $this->jsonSchema = new Schema(Utils::jsonDecode($response, false));
134 2
        }
135
136
        return $this->jsonSchema;
137 2
    }
138 2
139 1
    public function update(array $data)
140
    {
141
        // retrieve latest state so we can accurately produce a diff
142
        $this->retrieve();
143 1
144 1
        $schema     = $this->getSchema();
145 1
        $data       = (object) $data;
146
        $aliasNames = array_map(
147
            function (Alias $a) {
148 1
                return $a->propertyName;
149 1
            },
150 1
            $this->getAliases()
151
        );
152 1
153
        // formulate src and des structures
154 1
        $des = $schema->normalizeObject($data, $aliasNames);
155
        $src = $schema->normalizeObject($this, $aliasNames);
156
157 1
        // validate user input
158
        $schema->validate($des);
159 1
        if (!$schema->isValid()) {
160 1
            throw new \RuntimeException($schema->getErrorString());
161
        }
162 1
163
        // formulate diff
164 1
        $patch = new JsonPatch();
165 1
        $diff = $patch->disableRestrictedPropRemovals($patch->diff($src, $des), $schema->getPropertyPaths());
166
        $json = json_encode($diff, JSON_UNESCAPED_SLASHES);
167 1
168
        // execute patch operation
169 1
        $response = $this->execute($this->api->patchImage(), [
170 1
            'id'          => $this->id,
171
            'patchDoc'    => $json,
172 1
            'contentType' => 'application/openstack-images-v2.1-json-patch'
173
        ]);
174 1
175 1
        $this->populateFromResponse($response);
176 1
    }
177 1
178 1
    public function delete()
179 1
    {
180
        $this->executeWithState($this->api->deleteImage());
181 1
    }
182
183 1
    public function deactivate()
184 1
    {
185
        $this->executeWithState($this->api->deactivateImage());
186
    }
187 1
188
    public function reactivate()
189 1
    {
190
        $this->executeWithState($this->api->reactivateImage());
191
    }
192 1
193
    public function uploadData(StreamInterface $stream)
194 1
    {
195
        $this->execute($this->api->postImageData(), [
196
            'id'          => $this->id,
197 1
            'data'        => $stream,
198
            'contentType' => 'application/octet-stream',
199 1
        ]);
200
    }
201
202
    public function downloadData(): StreamInterface
203
    {
204
        $response = $this->executeWithState($this->api->getImageData());
205
        return $response->getBody();
206
    }
207
208
    public function addMember($memberId): Member
209
    {
210
        return $this->model(Member::class, ['imageId' => $this->id, 'id' => $memberId])->create([]);
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 create() does only exist in the following implementations of said interface: OpenStack\BlockStorage\v2\Models\Snapshot, OpenStack\BlockStorage\v2\Models\Volume, OpenStack\BlockStorage\v2\Models\VolumeType, OpenStack\Compute\v2\Models\Flavor, OpenStack\Compute\v2\Models\Keypair, OpenStack\Compute\v2\Models\Server, OpenStack\Identity\v3\Models\Credential, OpenStack\Identity\v3\Models\Domain, OpenStack\Identity\v3\Models\Endpoint, OpenStack\Identity\v3\Models\Group, OpenStack\Identity\v3\Models\Policy, OpenStack\Identity\v3\Models\Project, OpenStack\Identity\v3\Models\Role, OpenStack\Identity\v3\Models\Service, OpenStack\Identity\v3\Models\Token, OpenStack\Identity\v3\Models\User, OpenStack\Images\v2\Models\Image, OpenStack\Images\v2\Models\Member, OpenStack\Networking\v2\...ayer3\Models\FloatingIp, OpenStack\Networking\v2\...ns\Layer3\Models\Router, OpenStack\Networking\v2\...ps\Models\SecurityGroup, OpenStack\Networking\v2\...odels\SecurityGroupRule, OpenStack\Networking\v2\Models\LoadBalancer, OpenStack\Networking\v2\...adBalancerHealthMonitor, OpenStack\Networking\v2\...ls\LoadBalancerListener, OpenStack\Networking\v2\Models\LoadBalancerMember, OpenStack\Networking\v2\Models\LoadBalancerPool, OpenStack\Networking\v2\Models\Network, OpenStack\Networking\v2\Models\Port, OpenStack\Networking\v2\Models\Subnet, 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...
211
    }
212
213
    public function listMembers(): \Generator
214
    {
215
        return $this->model(Member::class)->enumerate($this->api->getImageMembers(), ['imageId' => $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...
216
    }
217
218
    public function getMember($memberId): Member
219
    {
220
        return $this->model(Member::class, ['imageId' => $this->id, 'id' => $memberId]);
221
    }
222
}
223