Completed
Pull Request — master (#427)
by
unknown
14:58
created

GoogleCloudClientStorage::read()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 8
Ratio 100 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 8
loc 8
rs 9.4285
cc 1
eloc 6
nc 1
nop 1
1
<?php
2
namespace Gaufrette\Adapter;
3
4
use Gaufrette\Adapter;
5
use Gaufrette\Adapter\MetadataSupporter;
6
use Gaufrette\Adapter\ResourcesSupporter;
7
use Gaufrette\Adapter\ListKeysAware;
8
9
/**
10
 * Google Cloud Storage adapter using the Google Cloud Client Library for PHP
11
 * http://googlecloudplatform.github.io/google-cloud-php/
12
 *
13
 * @package Gaufrette
14
 * @author  Lech Buszczynski <[email protected]>
15
 */
16
class GoogleCloudClientStorage implements Adapter, MetadataSupporter, ResourcesSupporter, ListKeysAware
17
{
18
    protected $storageClient;
19
    protected $bucket;
20
    protected $bucketValidated;
21
    protected $options      = array();
22
    protected $metadata     = array();
23
    protected $resources    = array();
24
25
    /**
26
     * @param Google\Cloud\Storage\StorageClient    $service    Authenticated storage client class
0 ignored issues
show
Bug introduced by
There is no parameter named $service. 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...
27
     * @param string                                $bucketName Name of the bucket
28
     * @param array                                 $options    Options are: "directory" and "acl" (see https://cloud.google.com/storage/docs/access-control/lists)
29
     */
30
    public function __construct(\Google\Cloud\Storage\StorageClient $storageClient, $bucketName, $options = array())
31
    {
32
        $this->storageClient = $storageClient;
33
        $this->setBucket($bucketName);
34
        $this->options = array_replace_recursive(
35
            array(
36
                'directory' => '',
37
                'acl'       => array()
38
            ),
39
            $options
40
        );
41
    }
42
    
43
    /**
44
     * Get adapter options
45
     * 
46
     * @return  array
47
     */
48
    public function getOptions()
49
    {
50
        return $this->options;
51
    }
52
53
    /**
54
     * Set adapter options
55
     * 
56
     * @param   array   $options
57
     */
58
    public function setOptions($options)
59
    {
60
        $this->options = array_replace($this->options, $options);
61
    }
62
    
63
    protected function computePath($key)
64
    {
65
        if (strlen($this->options['directory']))
66
        {
67
            if (strcmp(substr($this->options['directory'], -1), '/') == 0)
68
            {
69
                return $this->options['directory'].$key;
70
            }
71
            return $this->options['directory'].'/'.$key;
72
        }
73
        return $key;
74
    }
75
    
76
    protected function isBucket()
77
    {
78
        if ($this->bucketValidated === true)
79
        {
80
            return true;
81
        } elseif (!$this->bucket->exists()) {
82
            throw new \RuntimeException(sprintf('Bucket %s does not exist.', $this->bucket->name()));
83
        }
84
        $this->bucketValidated = true;
85
        return true;
86
    }
87
    
88
    public function setBucket($name)
89
    {
90
        $this->bucketValidated = null;
91
        $this->bucket = $this->storageClient->bucket($name);       
92
        $this->isBucket();
93
    }
94
    
95
    public function getBucket()
96
    {
97
        return $this->bucket;
98
    }
99
    
100
    /**
101
     * {@inheritdoc}
102
     */
103 View Code Duplication
    public function read($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...
104
    {   
105
        $this->isBucket();     
106
        $object = $this->bucket->object($this->computePath($key));
107
        $info = $object->info();
108
        $this->setResources($key, $info);
109
        return $object->downloadAsString();
110
    }
111
    
112
    /**
113
     * {@inheritdoc}
114
     */
115
    public function write($key, $content)
116
    {
117
        $this->isBucket();
118
        
119
        $options = array(
120
            'resumable'     => true,
121
            'name'          => $this->computePath($key),
122
            'metadata'      => $this->getMetadata($key),
123
        );
124
125
        $this->bucket->upload(
126
            $content,
127
            $options
128
        );
129
        
130
        $this->updateKeyProperties($key,
131
            array(
132
                'acl'       => $this->options['acl'],
133
                'metadata'  => $this->getMetadata($key)
134
            )
135
        );
136
        
137
        $size = $this->getResourceByName($key, 'size');
138
        
139
        return $size === null ? false : $size;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $size === null ? false : $size; (array|string) is incompatible with the return type declared by the interface Gaufrette\Adapter::write of type integer|boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
140
    }
141
    
142
    /**
143
     * {@inheritdoc}
144
     */
145 View Code Duplication
    public function exists($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...
146
    {
147
        $this->isBucket();
148
        $object = $this->bucket->object($this->computePath($key));
149
        if ($object->exists())
150
        {
151
            return true;
152
        }
153
        return false;
154
    }
155
    
156
    /**
157
     * {@inheritdoc}
158
     */
159
    public function isDirectory($key)
160
    {
161
        if ($this->exists($key . '/'))
162
        {
163
            return true;
164
        }
165
        return false;
166
    }
167
    
168
    /**
169
     * {@inheritdoc}
170
     */
171
    public function listKeys($prefix = null)
172
    {
173
        $this->isBucket();        
174
        $keys = array();        
175
        if ($prefix === null)
176
        {
177
            $prefix = $this->options['directory'];
178
        } else {
179
            $prefix = $this->computePath($prefix);
180
        }
181
        foreach ($this->bucket->objects(array('prefix' => $prefix)) as $e)
182
        {
183
            $keys[] = $e->name();
184
        }
185
        sort($keys);
186
        return $keys;
187
    }
188
    
189
    /**
190
     * {@inheritdoc}
191
     */
192
    public function keys()
193
    {
194
        return $this->listKeys();
195
    }
196
197
    /**
198
     * {@inheritdoc}
199
     */
200 View Code Duplication
    public function mtime($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...
201
    {
202
        $this->isBucket();
203
        $object = $object = $this->bucket->object($this->computePath($key));
204
        $info = $object->info();
205
        $this->setResources($key, $info);
206
        return strtotime($info['updated']);
207
    }
208
    
209
    /**
210
     * {@inheritdoc}
211
     */
212 View Code Duplication
    public function delete($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...
213
    {
214
        $this->isBucket();
215
        $object = $this->bucket->object($this->computePath($key));
216
        $object->delete();
217
        $this->setMetadata($key, null);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
218
        return true;
219
    }
220
    
221
    /**
222
     * {@inheritdoc}
223
     */
224
    public function rename($sourceKey, $targetKey)
225
    {
226
        $this->isBucket();
227
        
228
        $metadata = $this->getMetadata($sourceKey);
0 ignored issues
show
Unused Code introduced by
$metadata is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
229
        
230
        $sourceKey = $this->computePath($sourceKey);
231
        $targetKey = $this->computePath($targetKey);
232
        
233
        $object = $this->bucket->object($sourceKey);
234
        
235
        $copiedObject = $object->copy($this->bucket,
236
            array(
237
                'name' => $targetKey
238
            )
239
        );
240
        
241
        if ($copiedObject->exists())
242
        {
243
            $this->updateKeyProperties($targetKey,
244
                array(
245
                    'acl'       => $this->options['acl'],
246
                    'metadata'  => $this->getMetadata($sourceKey)
247
                )
248
            );
249
            $this->setMetadata($targetKey, $this->getMetadata($sourceKey));
250
            $this->setMetadata($sourceKey, null);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
251
            $object->delete();
252
            return true;
253
        }
254
        return false;
255
    }
256
    
257
    /**
258
     * {@inheritdoc}
259
     */
260
    public function setMetadata($key, $metadata)
261
    {
262
        $this->metadata[$key] = $metadata;
263
    }
264
265
    /**
266
     * {@inheritdoc}
267
     */
268
    public function getMetadata($key)
269
    {
270
        if (!isset($this->metadata[$key]) && $this->exists($key))
271
        {
272
            $data = $this->bucket->object($key)->info();
273
            if (isset($data['metadata']))
274
            {
275
                $this->metadata[$key] = $data['metadata'];
276
            }
277
        }
278
        return isset($this->metadata[$key]) ? $this->metadata[$key] : array();
279
    }
280
    
281
    /**
282
     * {@inheritdoc}
283
     */
284
    public function setResources($key, $data)
285
    {
286
        $this->resources[$key] = $data;
287
    }
288
    
289
    /**
290
     * {@inheritdoc}
291
     */
292
    public function getResources($key)
293
    {
294
        return isset($this->resources[$key]) ? $this->resources[$key] : array();
295
    }
296
    
297
    /**
298
     * {@inheritdoc}
299
     */
300
    public function getResourceByName($key, $resourceName)
301
    {
302
        return isset($this->resources[$key][$resourceName]) ? $this->resources[$key][$resourceName] : null;
303
    }
304
    
305
    /**
306
     * Sets ACL and metadata information.
307
     * 
308
     * @param   string  $key
309
     * @param   array   $options    Can contain "acl" and/or "metadata" arrays.
310
     * @return  boolean
311
     */
312
    protected function updateKeyProperties($key, $options = array())
313
    {
314
        if ($this->exists($key) === false)
315
        {
316
            return false;
317
        }
318
        
319
        $object = $this->bucket->object($this->computePath($key));
320
        
321
        $properties = array_replace_recursive(
322
            array(
323
                'acl'       => array(),
324
                'metadata'  => array()
325
            ), $options
326
        );
327
328
        $acl = $object->acl();
329
        foreach ($properties['acl'] as $k => $v)
330
        {
331
            $acl->add($k, $v);
332
        }
333
        $object->update(array('metadata' => $properties['metadata']));
334
335
        $info = $object->info();
336
337
        $this->setResources($key, $info);
338
        return true;
339
    }
340
}
341