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.

Container::createLargeObject()   C
last analyzed

Complexity

Conditions 7
Paths 32

Size

Total Lines 37
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 37
ccs 25
cts 25
cp 1
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 22
nc 32
nop 1
crap 7
1
<?php declare(strict_types=1);
2
3
namespace OpenStack\ObjectStore\v1\Models;
4
5
use GuzzleHttp\Promise\Promise;
6
use GuzzleHttp\Psr7\LimitStream;
7
use Psr\Http\Message\ResponseInterface;
8
use OpenStack\Common\Error\BadResponseError;
9
use OpenStack\Common\Resource\OperatorResource;
10
use OpenStack\Common\Resource\Creatable;
11
use OpenStack\Common\Resource\Deletable;
12
use OpenStack\Common\Resource\HasMetadata;
13
use OpenStack\Common\Resource\Listable;
14
use OpenStack\Common\Resource\Retrievable;
15
16
/**
17
 * @property \OpenStack\ObjectStore\v1\Api $api
18
 */
19
class Container extends OperatorResource implements Creatable, Deletable, Retrievable, Listable, HasMetadata
20
{
21
    use MetadataTrait;
22
23
    const METADATA_PREFIX = 'X-Container-Meta-';
24
25
    /** @var int */
26
    public $objectCount;
27
28
    /** @var int */
29
    public $bytesUsed;
30
31
    /** @var string */
32
    public $name;
33
34
    /** @var array */
35
    public $metadata;
36
37
    protected $markerKey = 'name';
38
39
    /**
40
     * {@inheritdoc}
41
     */
42 5
    public function populateFromResponse(ResponseInterface $response): self
43
    {
44 5
        parent::populateFromResponse($response);
45
46 5
        $this->objectCount = $response->getHeaderLine('X-Container-Object-Count');
0 ignored issues
show
Documentation Bug introduced by
The property $objectCount was declared of type integer, but $response->getHeaderLine...ontainer-Object-Count') is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
47 5
        $this->bytesUsed = $response->getHeaderLine('X-Container-Bytes-Used');
0 ignored issues
show
Documentation Bug introduced by
The property $bytesUsed was declared of type integer, but $response->getHeaderLine...-Container-Bytes-Used') is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
48 5
        $this->metadata = $this->parseMetadata($response);
49 5
50
        return $this;
51
    }
52
53
    /**
54
     * Retrieves a collection of object resources in the form of a generator.
55
     *
56
     * @param array         $options {@see \OpenStack\ObjectStore\v1\Api::getContainer}
57
     * @param callable|null $mapFn   Allows a function to be mapped over each element.
58
     *
59 1
     * @return \Generator
60
     */
61 1
    public function listObjects(array $options = [], callable $mapFn = null): \Generator
62 1
    {
63
        $options = array_merge($options, ['name' => $this->name, 'format' => 'json']);
64
        return $this->model(Object::class)->enumerate($this->api->getContainer(), $options, $mapFn);
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...
65
    }
66
67
    /**
68 1
     * {@inheritdoc}
69
     */
70 1
    public function retrieve()
71 1
    {
72 1
        $response = $this->executeWithState($this->api->headContainer());
73
        $this->populateFromResponse($response);
74
    }
75
76
    /**
77
     * @param array $data {@see \OpenStack\ObjectStore\v1\Api::putContainer}
78
     *
79 3
     * @return $this
80
     */
81 3
    public function create(array $data): Creatable
82
    {
83 3
        $response = $this->execute($this->api->putContainer(), $data);
84 3
85
        $this->populateFromResponse($response);
86 3
        $this->name = $data['name'];
87
88
        return $this;
89
    }
90
91
    /**
92 1
     * {@inheritdoc}
93
     */
94 1
    public function delete()
95 1
    {
96
        $this->executeWithState($this->api->deleteContainer());
97
    }
98
99
    /**
100 1
     * {@inheritdoc}
101
     */
102 1
    public function mergeMetadata(array $metadata)
103 1
    {
104
        $response = $this->execute($this->api->postContainer(), ['name' => $this->name, 'metadata' => $metadata]);
105
        $this->metadata = $this->parseMetadata($response);
106
    }
107
108
    /**
109 1
     * {@inheritdoc}
110
     */
111 View Code Duplication
    public function resetMetadata(array $metadata)
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...
112 1
    {
113 1
        $options = [
114 1
            'name'           => $this->name,
115 1
            'removeMetadata' => [],
116
            'metadata'       => $metadata,
117 1
        ];
118 1
119 1
        foreach ($this->getMetadata() as $key => $val) {
120 1
            if (!array_key_exists($key, $metadata)) {
121 1
                $options['removeMetadata'][$key] = 'True';
122
            }
123 1
        }
124 1
125
        $response = $this->execute($this->api->postContainer(), $options);
126
        $this->metadata = $this->parseMetadata($response);
127
    }
128
129
    /**
130 2
     * {@inheritdoc}
131
     */
132 2
    public function getMetadata(): array
133 2
    {
134
        $response = $this->executeWithState($this->api->headContainer());
135
        return $this->parseMetadata($response);
136
    }
137
138
    /**
139
     * Retrieves an Object and populates its `name` and `containerName` properties according to the name provided and
140
     * the name of this container. A HTTP call will not be executed by default - you need to call
141
     * {@see Object::retrieve} or {@see Object::download} on the returned Object object to do that.
142
     *
143
     * @param string $name The name of the object
144
     *
145 4
     * @return Object
146
     */
147 4
    public function getObject($name): Object
148
    {
149
        return $this->model(Object::class, ['containerName' => $this->name, 'name' => $name]);
150
    }
151
152
    /**
153
     * Identifies whether an object exists in this container.
154
     *
155
     * @param string $name The name of the object.
156
     *
157
     * @return bool TRUE if the object exists, FALSE if it does not.
158
     *
159
     * @throws BadResponseError For any other HTTP error which does not have a 404 Not Found status.
160 3
     * @throws \Exception       For any other type of fatal error.
161
     */
162 View Code Duplication
    public function objectExists(string $name): bool
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...
163 3
    {
164 1
        try {
165 2
            $this->getObject($name)->retrieve();
166 2
            return true;
167 1
        } catch (BadResponseError $e) {
168
            if ($e->getResponse()->getStatusCode() === 404) {
169 1
                return false;
170
            }
171
            throw $e;
172
        }
173
    }
174
175
    /**
176
     * Creates a single object according to the values provided.
177
     *
178
     * @param array $data {@see \OpenStack\ObjectStore\v1\Api::putObject}
179
     *
180 2
     * @return Object
181
     */
182 2
    public function createObject(array $data): Object
183
    {
184
        return $this->model(Object::class)->create($data + ['containerName' => $this->name]);
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...
185
    }
186
187
    /**
188
     * Creates a Dynamic Large Object by chunking a file into smaller segments and uploading them into a holding
189
     * container. When this completes, a manifest file is uploaded which references the prefix of the segments,
190
     * allowing concatenation when a request is executed against the manifest.
191
     *
192
     * @param array  $data                     {@see \OpenStack\ObjectStore\v1\Api::putObject}
193
     * @param int    $data['segmentSize']      The size in Bytes of each segment
0 ignored issues
show
Bug introduced by
There is no parameter named $data['segmentSize']. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
194
     * @param string $data['segmentContainer'] The container to which each segment will be uploaded
0 ignored issues
show
Bug introduced by
There is no parameter named $data['segmentContainer']. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
195
     * @param string $data['segmentPrefix']    The prefix that will come before each segment. If omitted, a default
0 ignored issues
show
Bug introduced by
There is no parameter named $data['segmentPrefix']. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
196
     *                                         is used: name/timestamp/filesize
197
     *
198 1
     * @return Object
199
     */
200
    public function createLargeObject(array $data): Object
201 1
    {
202
        /** @var \Psr\Http\Message\StreamInterface $stream */
203 1
        $stream = $data['stream'];
204 1
205 1
        $segmentSize      = isset($data['segmentSize']) ? $data['segmentSize'] : 1073741824;
206 1
        $segmentContainer = isset($data['segmentContainer']) ? $data['segmentContainer'] : $this->name . '_segments';
207 1
        $segmentPrefix    = isset($data['segmentPrefix'])
208
            ? $data['segmentPrefix']
209
            : sprintf("%s/%s/%d", $data['name'], microtime(true), $stream->getSize());
210 1
211 1
        /** @var \OpenStack\ObjectStore\v1\Service $service */
212 1
        $service = $this->getService();
213 1
        if (!$service->containerExists($segmentContainer)) {
214
            $service->createContainer(['name' => $segmentContainer]);
215 1
        }
216 1
217
        $promises = [];
218 1
        $count    = 0;
219 1
220 1
        while (!$stream->eof() && $count < round($stream->getSize() / $segmentSize)) {
221 1
            $promises[] = $this->model(Object::class)->createAsync([
0 ignored issues
show
Bug introduced by
The method createAsync() does not seem to exist on object<OpenStack\Common\...urce\ResourceInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
222 1
                'name'          => sprintf("%s/%d", $segmentPrefix, ++$count),
223 1
                'stream'        => new LimitStream($stream, $segmentSize, ($count - 1) * $segmentSize),
224 1
                'containerName' => $segmentContainer,
225
            ]);
226
        }
227 1
228 1
        /** @var Promise $p */
229
        $p = \GuzzleHttp\Promise\all($promises);
230 1
        $p->wait();
231 1
232 1
        return $this->createObject([
233 1
            'name'           => $data['name'],
234
            'objectManifest' => sprintf("%s/%s", $segmentContainer, $segmentPrefix),
235
        ]);
236
    }
237
}
238