Completed
Pull Request — master (#427)
by
unknown
10:07
created

GoogleCloudClientStorage::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 13
rs 9.4285
cc 1
eloc 9
nc 1
nop 3
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
        $this->options['directory'] = rtrim($this->options['directory'], '/');
42
    }
43
    
44
    /**
45
     * Get adapter options
46
     * 
47
     * @return  array
48
     */
49
    public function getOptions()
50
    {
51
        return $this->options;
52
    }
53
54
    /**
55
     * Set adapter options
56
     * 
57
     * @param   array   $options
58
     */
59
    public function setOptions($options)
60
    {
61
        $this->options = array_replace($this->options, $options);
62
    }
63
    
64
    protected function computePath($key = null)
65
    {
66
        if (strlen($this->options['directory']))
67
        {
68
            return $this->options['directory'].'/'.$key;
69
        }
70
        return $key;
71
    }
72
    
73
    protected function isBucket()
74
    {
75
        if ($this->bucketValidated === true)
76
        {
77
            return true;
78
        } elseif (!$this->bucket->exists()) {
79
            throw new \RuntimeException(sprintf('Bucket %s does not exist.', $this->bucket->name()));
80
        }
81
        $this->bucketValidated = true;
82
        return true;
83
    }
84
    
85
    public function setBucket($name)
86
    {
87
        $this->bucketValidated = null;
88
        $this->bucket = $this->storageClient->bucket($name);       
89
        $this->isBucket();
90
    }
91
    
92
    public function getBucket()
93
    {
94
        return $this->bucket;
95
    }
96
    
97
    /**
98
     * {@inheritdoc}
99
     */
100 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...
101
    {   
102
        $this->isBucket();     
103
        $object = $this->bucket->object($this->computePath($key));
104
        $info = $object->info();
105
        $this->setResources($key, $info);
106
        return $object->downloadAsString();
107
    }
108
    
109
    /**
110
     * {@inheritdoc}
111
     */
112
    public function write($key, $content)
113
    {
114
        $this->isBucket();
115
        
116
        $options = array(
117
            'resumable'     => true,
118
            'name'          => $this->computePath($key),
119
            'metadata'      => $this->getMetadata($key),
120
        );
121
122
        $this->bucket->upload(
123
            $content,
124
            $options
125
        );
126
        
127
        $this->updateKeyProperties($key,
128
            array(
129
                'acl'       => $this->options['acl'],
130
                'metadata'  => $this->getMetadata($key)
131
            )
132
        );
133
134
        $size = $this->getResourceByName($key, 'size');
135
        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...
136
    }
137
    
138
    /**
139
     * {@inheritdoc}
140
     */
141
    public function exists($key)
142
    {
143
        $this->isBucket();
144
        $object = $this->bucket->object($this->computePath($key));
145
        return $object->exists();
146
    }
147
    
148
    /**
149
     * {@inheritdoc}
150
     */
151
    public function isDirectory($key)
152
    {
153
        return $this->exists($this->computePath(rtrim($key, '/')).'/');
154
    }
155
    
156
    /**
157
     * {@inheritdoc}
158
     */
159
    public function listKeys($prefix = null)
160
    {
161
        $this->isBucket();        
162
        $keys = array();
163
        
164
        foreach ($this->bucket->objects(array('prefix' => $this->computePath($prefix))) as $e)
165
        {
166
            $keys[] = $e->name();
167
        }
168
        sort($keys);
169
        return $keys;
170
    }
171
    
172
    /**
173
     * {@inheritdoc}
174
     */
175
    public function keys()
176
    {
177
        return $this->listKeys();
178
    }
179
180
    /**
181
     * {@inheritdoc}
182
     */
183 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...
184
    {
185
        $this->isBucket();
186
        $object = $object = $this->bucket->object($this->computePath($key));
187
        $info = $object->info();
188
        $this->setResources($key, $info);
189
        return strtotime($info['updated']);
190
    }
191
    
192
    /**
193
     * {@inheritdoc}
194
     */
195
    public function delete($key)
196
    {
197
        $this->isBucket();
198
        $object = $this->bucket->object($this->computePath($key));
199
        $object->delete();
200
        $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...
201
        return true;
202
    }
203
    
204
    /**
205
     * {@inheritdoc}
206
     */
207
    public function rename($sourceKey, $targetKey)
208
    {
209
        $this->isBucket();
210
        
211
        $pathedSourceKey = $this->computePath($sourceKey);
212
        $pathedTargetKey = $this->computePath($targetKey);
213
                
214
        $object = $this->bucket->object($pathedSourceKey);
215
        
216
        $copiedObject = $object->copy($this->bucket,
217
            array(
218
                'name' => $pathedTargetKey
219
            )
220
        );
221
        
222
        if ($copiedObject->exists())
223
        {
224
            $this->updateKeyProperties($targetKey,
225
                array(
226
                    'acl'       => $this->options['acl'],
227
                    'metadata'  => $this->getMetadata($sourceKey)
228
                )
229
            );
230
            $this->setMetadata($targetKey, $this->getMetadata($sourceKey));
231
            $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...
232
            $object->delete();
233
            return true;
234
        }
235
        return false;
236
    }
237
    
238
    /**
239
     * {@inheritdoc}
240
     */
241
    public function setMetadata($key, $metadata)
242
    {
243
        $this->metadata[$this->computePath($key)] = $metadata;
244
    }
245
246
    /**
247
     * {@inheritdoc}
248
     */
249
    public function getMetadata($key)
250
    {
251
        $pathedKey = $this->computePath($key);
252
        if (!isset($this->metadata[$pathedKey]) && $this->exists($pathedKey))
253
        {
254
            $data = $this->bucket->object($pathedKey)->info();
255
            if (isset($data['metadata']))
256
            {
257
                $this->metadata[$pathedKey] = $data['metadata'];
258
            }
259
        }
260
        return isset($this->metadata[$pathedKey]) ? $this->metadata[$pathedKey] : array();
261
    }
262
    
263
    /**
264
     * {@inheritdoc}
265
     */
266
    public function setResources($key, $data)
267
    {
268
        $this->resources[$this->computePath($key)] = $data;
269
    }
270
    
271
    /**
272
     * {@inheritdoc}
273
     */
274
    public function getResources($key)
275
    {
276
        $pathedKey = $this->computePath($key);
277
        return isset($this->resources[$pathedKey]) ? $this->resources[$pathedKey] : array();
278
    }
279
    
280
    /**
281
     * {@inheritdoc}
282
     */
283
    public function getResourceByName($key, $resourceName)
284
    {
285
        $pathedKey = $this->computePath($key);
286
        return isset($this->resources[$pathedKey][$resourceName]) ? $this->resources[$pathedKey][$resourceName] : null;
287
    }
288
    
289
    /**
290
     * Sets ACL and metadata information.
291
     * 
292
     * @param   string  $key
293
     * @param   array   $options    Can contain "acl" and/or "metadata" arrays.
294
     * @return  boolean
295
     */
296
    protected function updateKeyProperties($key, $options = array())
297
    {
298
        if ($this->exists($key) === false)
299
        {
300
            return false;
301
        }
302
      
303
        $object = $this->bucket->object($this->computePath($key));
304
        
305
        $properties = array_replace_recursive(
306
            array(
307
                'acl'       => array(),
308
                'metadata'  => array()
309
            ), $options
310
        );
311
312
        $acl = $object->acl();
313
        foreach ($properties['acl'] as $k => $v)
314
        {
315
            $acl->add($k, $v);
316
        }
317
        $object->update(array('metadata' => $properties['metadata']));
318
319
        $info = $object->info();
320
321
        $this->setResources($key, $info);
322
        return true;
323
    }
324
}
325