Completed
Pull Request — master (#7)
by
unknown
03:20
created

GridFSAdapter::has()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace League\Flysystem\GridFS;
4
5
use BadMethodCallException;
6
use League\Flysystem\Adapter\AbstractAdapter;
7
use League\Flysystem\Adapter\Polyfill\NotSupportingVisibilityTrait;
8
use League\Flysystem\Adapter\Polyfill\StreamedCopyTrait;
9
use League\Flysystem\Adapter\Polyfill\StreamedReadingTrait;
10
use League\Flysystem\Config;
11
use League\Flysystem\Util;
12
use LogicException;
13
use MongoGridFs;
14
use MongoGridFSException;
15
use MongoGridFSFile;
16
use MongoRegex;
17
18
class GridFSAdapter extends AbstractAdapter
19
{
20
    use NotSupportingVisibilityTrait;
21
    use StreamedCopyTrait;
22
    use StreamedReadingTrait;
23
24
    /**
25
     * @var MongoGridFs Mongo GridFS client
26
     */
27
    protected $client;
28
29
    /**
30
     * Constructor.
31
     *
32
     * @param MongoGridFs $client
33
     */
34
    public function __construct(MongoGridFs $client)
35
    {
36
        $this->client  = $client;
37
    }
38
39
    /**
40
     * Get the MongoGridFs instance.
41
     *
42
     * @return MongoGridFs
43
     */
44
    public function getClient()
45
    {
46
        return $this->client;
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function has($path)
53
    {
54
        $location = $this->applyPathPrefix($path);
55
56
        return $this->client->findOne($location) !== null;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62
    public function write($path, $contents, Config $config)
63
    {
64
        $metadata = [];
65
66
        if ($config->has('mimetype')) {
67
            $metadata['mimetype'] = $config->get('mimetype');
68
        }
69
70
        return $this->writeObject($path, $contents, [
71
            'filename' => $path,
72
            'metadata' => $metadata,
73
        ]);
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79
    public function writeStream($path, $resource, Config $config)
80
    {
81
        return $this->write($path, $resource, $config);
0 ignored issues
show
Documentation introduced by
$resource is of type resource, but the function expects a string.

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...
82
    }
83
84
    /**
85
     * {@inheritdoc}
86
     */
87
    public function update($path, $contents, Config $config)
88
    {
89
        return $this->write($path, $contents, $config);
90
    }
91
92
    /**
93
     * {@inheritdoc}
94
     */
95
    public function updateStream($path, $resource, Config $config)
96
    {
97
        return $this->writeStream($path, $resource, $config);
98
    }
99
100
    /**
101
     * {@inheritdoc}
102
     */
103
    public function getMetadata($path)
104
    {
105
        $result = $this->client->findOne($path);
106
107
        return $this->normalizeGridFSFile($result, $path);
108
    }
109
110
    /**
111
     * {@inheritdoc}
112
     */
113
    public function getMimetype($path)
114
    {
115
        return $this->getMetadata($path);
116
    }
117
118
    /**
119
     * {@inheritdoc}
120
     */
121
    public function getSize($path)
122
    {
123
        return $this->getMetadata($path);
124
    }
125
126
    /**
127
     * {@inheritdoc}
128
     */
129
    public function getTimestamp($path)
130
    {
131
        return $this->getMetadata($path);
132
    }
133
134
    /**
135
     * {@inheritdoc}
136
     */
137
    public function delete($path)
138
    {
139
        $file = $this->client->findOne($path);
140
141
        return $file && $this->client->delete($file->file['_id']) !== false;
142
    }
143
144
    /**
145
     * {@inheritdoc}
146
     */
147
    public function read($path)
148
    {
149
        $file = $this->client->findOne($path);
150
151
        return $file ? ['contents' => $file->getBytes()] : false;
152
    }
153
154
    /**
155
     * {@inheritdoc}
156
     */
157
    public function rename($path, $newpath)
158
    {
159
        return $this->copy($path, $newpath) && $this->delete($path);
160
    }
161
162
    /**
163
     * {@inheritdoc}
164
     */
165
    public function createDir($path, Config $config)
166
    {
167
        throw new LogicException(get_class($this).' does not support directory creation.');
168
    }
169
170
    /**
171
     * {@inheritdoc}
172
     */
173
    public function deleteDir($path)
174
    {
175
        $prefix = rtrim($this->applyPathPrefix($path), '/').'/';
176
177
        $result = $this->client->remove([
178
            'filename' => new MongoRegex(sprintf('/^%s/', $prefix)),
179
        ]);
180
181
        return $result === true;
182
    }
183
184
    /**
185
     * {@inheritdoc}
186
     *
187
     * @todo Implement recursive listing.
188
     */
189
    public function listContents($dirname = '', $recursive = false)
190
    {
191
        if ($recursive) {
192
            throw new BadMethodCallException('Recursive listing is not yet implemented');
193
        }
194
195
        $keys = [];
196
        $cursor = $this->client->find([
197
            'filename' => new MongoRegex(sprintf('/^%s/', $dirname)),
198
        ]);
199
        foreach ($cursor as $file) {
200
            $keys[] = $this->normalizeGridFSFile($file);
201
        }
202
203
        return Util::emulateDirectories($keys);
204
    }
205
206
    /**
207
     * Write an object to GridFS.
208
     *
209
     * @param array $metadata
210
     *
211
     * @return array normalized file representation
212
     */
213
    protected function writeObject($path, $content, array $metadata)
214
    {
215
        try {
216
            if (is_resource($content)) {
217
                $id = $this->client->storeFile($content, $metadata);
218
            } else {
219
                $id = $this->client->storeBytes($content, $metadata);
220
            }
221
222
            // Create index on files/filename
223
            $this->ensureIndex();
224
        } catch (MongoGridFSException $e) {
225
            return false;
226
        }
227
228
        $file = $this->client->findOne(['_id' => $id]);
229
230
        return $this->normalizeGridFSFile($file, $path);
231
    }
232
233
    /**
234
     * Normalize a MongoGridFs file to a response.
235
     *
236
     * @param MongoGridFSFile $file
237
     * @param string          $path
238
     *
239
     * @return array
240
     */
241
    protected function normalizeGridFSFile(MongoGridFSFile $file, $path = null)
242
    {
243
        $result = [
244
            'path'      => trim($path ?: $file->getFilename(), '/'),
245
            'type'      => 'file',
246
            'size'      => $file->getSize(),
247
            'timestamp' => $file->file['uploadDate']->sec,
248
        ];
249
250
        $result['dirname'] = Util::dirname($result['path']);
251
252
        if (isset($file->file['metadata']) && !empty($file->file['metadata']['mimetype'])) {
253
            $result['mimetype'] = $file->file['metadata']['mimetype'];
254
        }
255
256
        return $result;
257
    }
258
259
    /**
260
     * Creates index on filename field
261
     */
262
    protected function ensureIndex()
263
    {
264
        $indexes = $this->client->getIndexInfo();
265
        foreach($indexes as $index) {
266
            if ($index['name'] == 'filename_1') {
267
                return;
268
            }
269
        }
270
271
        // Looks like there is not index
272
        if (method_exists($this->client, 'createIndex')) {
273
            $this->client->createIndex(['filename' => \MongoCollection::ASCENDING]);
274
        }
275
    }
276
}
277