-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathFileStorageBehavior.php
More file actions
369 lines (322 loc) · 10.4 KB
/
FileStorageBehavior.php
File metadata and controls
369 lines (322 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
<?php
declare(strict_types = 1);
namespace Burzum\FileStorage\Model\Behavior;
use ArrayObject;
use Burzum\FileStorage\FileStorage\DataTransformer;
use Burzum\FileStorage\FileStorage\DataTransformerInterface;
use Cake\Core\Configure;
use Cake\Datasource\EntityInterface;
use Cake\Event\EventDispatcherTrait;
use Cake\Event\EventInterface;
use Cake\ORM\Behavior;
use League\Flysystem\AdapterInterface;
use Phauthentic\Infrastructure\Storage\FileInterface;
use Phauthentic\Infrastructure\Storage\FileStorage;
use Phauthentic\Infrastructure\Storage\Processor\ProcessorInterface;
use RuntimeException;
use Throwable;
/**
* File Storage Behavior.
*
* @author Florian Krämer
* @copyright 2012 - 2020 Florian Krämer
* @license MIT
*/
class FileStorageBehavior extends Behavior
{
use EventDispatcherTrait;
/**
* @var \Phauthentic\Infrastructure\Storage\FileStorage
*/
protected $fileStorage;
/**
* @var \Burzum\FileStorage\FileStorage\DataTransformerInterface
*/
protected $transformer;
/**
* @var \Phauthentic\Infrastructure\Storage\Processor\ProcessorInterface
*/
protected $processor;
/**
* Default config
*
* @var array
*/
protected $_defaultConfig = [
'defaultStorageConfig' => 'Local',
'ignoreEmptyFile' => true,
'fileField' => 'file',
'fileStorage' => null,
'fileProcessor' => null,
];
/**
* @inheritDoc
*
* @throws \RuntimeException
*/
public function initialize(array $config): void
{
parent::initialize($config);
if ($this->getConfig('fileStorage') instanceof FileStorage) {
$this->fileStorage = $this->getConfig('fileStorage');
} else {
throw new RuntimeException(
'Missing or invalid fileStorage config key'
);
}
if (!$this->getConfig('dataTransformer') instanceof DataTransformerInterface) {
$this->transformer = new DataTransformer(
$this->getTable()
);
}
//$this->processors = (array)$this->getConfig('processors');
}
/**
* @param string $configName
*
* @return \League\Flysystem\AdapterInterface
*/
public function getStorageAdapter(string $configName): AdapterInterface
{
return $this->fileStorage->getStorage($configName);
}
/**
* Checks if a file upload is present.
*
* @param \Cake\Datasource\EntityInterface|\ArrayObject $entity
*
* @return bool
*/
protected function isFileUploadPresent($entity)
{
$field = $this->getConfig('fileField');
if ($this->getConfig('ignoreEmptyFile') === true) {
if (!isset($entity[$field])) {
return false;
}
/** @var \Psr\Http\Message\UploadedFileInterface|array $file */
$file = $entity[$field];
if (!is_array($file)) {
return $file->getError() !== UPLOAD_ERR_NO_FILE;
}
return $file['error'] !== UPLOAD_ERR_NO_FILE;
}
return true;
}
/**
* beforeMarshal callback
*
* @param \Cake\Event\EventInterface $event
* @param \ArrayObject $data
* @param \ArrayObject $options
*
* @return void
*/
public function beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObject $options): void
{
if ($this->isFileUploadPresent($data)) {
$this->getFileInfoFromUpload($data);
}
}
/**
* beforeSave callback
*
* @param \Cake\Event\EventInterface $event
* @param \Cake\Datasource\EntityInterface $entity
* @param \ArrayObject $options
*
* @return void
*/
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void
{
if (!$this->isFileUploadPresent($entity)) {
return;
}
$this->checkEntityBeforeSave($entity);
$this->dispatchEvent('FileStorage.beforeSave', [
'entity' => $entity,
'storageAdapter' => $this->getStorageAdapter($entity->get('adapter')),
], $this->getTable());
}
/**
* afterSave callback
*
* @param \Cake\Event\EventInterface $event
* @param \Cake\Datasource\EntityInterface $entity
* @param \ArrayObject $options
*
* @throws \Exception
*
* @return void
*/
public function afterSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void
{
if (!$this->isFileUploadPresent($entity)) {
return;
}
if ($entity->isNew()) {
try {
$file = $this->entityToFileObject($entity);
$file = $this->fileStorage->store($file);
// TODO: move into stack processing
$file = $this->processImages($file, $entity);
$processor = $this->getFileProcessor();
$file = $processor->process($file);
$entity = $this->fileObjectToEntity($file, $entity);
$this->getTable()->save(
$entity,
['callbacks' => false]
);
} catch (Throwable $exception) {
$this->getTable()->delete($entity);
throw $exception;
}
}
$this->dispatchEvent('FileStorage.afterSave', [
'entity' => $entity,
'storageAdapter' => $this->getStorageAdapter($entity->get('adapter')),
], $this->getTable());
}
/**
* checkEntityBeforeSave
*
* @param \Cake\Datasource\EntityInterface $entity
*
* @return void
*/
protected function checkEntityBeforeSave(EntityInterface $entity)
{
if ($entity->isNew()) {
if (!$entity->has('model')) {
$entity->set('model', $this->getTable()->getAlias());
}
if (!$entity->has('adapter')) {
$entity->set('adapter', $this->getConfig('defaultStorageConfig'));
}
}
}
/**
* afterDelete callback
*
* @param \Cake\Event\EventInterface $event
* @param \Cake\Datasource\EntityInterface $entity
* @param \ArrayObject $options
*
* @return void
*/
public function afterDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options): void
{
$this->dispatchEvent('FileStorage.afterDelete', [
'entity' => $entity,
], $this->getTable());
$file = $this->entityToFileObject($entity);
$this->fileStorage->remove($file);
}
/**
* Gets information about the file that is being uploaded.
*
* - gets the file size
* - gets the mime type
* - gets the extension if present
*
* @param array|\ArrayAccess $upload
* @param string $field
*
* @return void
*/
protected function getFileInfoFromUpload(&$upload, $field = 'file')
{
/** @var \Psr\Http\Message\UploadedFileInterface|array $uploadedFile */
$uploadedFile = $upload[$field];
if (!is_array($uploadedFile)) {
$upload['filesize'] = $uploadedFile->getSize();
$upload['mime_type'] = $uploadedFile->getClientMediaType();
$upload['extension'] = pathinfo((string)$uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
$upload['filename'] = $uploadedFile->getClientFilename();
} else {
$upload['filesize'] = $uploadedFile['size'];
$upload['mime_type'] = $uploadedFile['type'];
$upload['extension'] = pathinfo($uploadedFile['name'], PATHINFO_EXTENSION);
$upload['filename'] = $uploadedFile['name'];
}
}
/**
* Don't use Table::deleteAll() if you don't want to end up with orphaned
* files! The reason for that is that deleteAll() doesn't fire the
* callbacks. So the events that will remove the files won't get fired.
*
* @param array $conditions Query::where() array structure.
*
* @return int Number of deleted records / files
*/
public function deleteAllFiles(array $conditions)
{
$table = $this->getTable();
$results = $table->find()
->select((array)$table->getPrimaryKey())
->where($conditions)
->all();
if ($results->count() > 0) {
foreach ($results as $result) {
$table->delete($result);
}
}
return $results->count();
}
/**
* @param \Cake\Datasource\EntityInterface $entity Entity
*
* @return \Phauthentic\Infrastructure\Storage\FileInterface
*/
public function entityToFileObject(EntityInterface $entity): FileInterface
{
return $this->transformer->entityToFileObject($entity);
}
/**
* @param \Phauthentic\Infrastructure\Storage\FileInterface $file File
* @param \Cake\Datasource\EntityInterface|null $entity
*
* @return \Cake\Datasource\EntityInterface
*/
public function fileObjectToEntity(FileInterface $file, ?EntityInterface $entity)
{
return $this->transformer->fileObjectToEntity($file, $entity);
}
/**
* Processes images
*
* @param \Phauthentic\Infrastructure\Storage\FileInterface $file File
* @param \Cake\Datasource\EntityInterface $entity
*
* @return \Phauthentic\Infrastructure\Storage\FileInterface
*/
public function processImages(FileInterface $file, EntityInterface $entity): FileInterface
{
$imageSizes = (array)Configure::read('FileStorage.imageVariants');
$model = $file->model();
$collection = $entity->get('collection');
if (!isset($imageSizes[$model][$collection])) {
return $file;
}
$file = $file->withVariants($imageSizes[$model][$collection]);
return $file;
}
/**
* @throws \RuntimeException
*
* @return \Phauthentic\Infrastructure\Storage\Processor\ProcessorInterface
*/
protected function getFileProcessor(): ProcessorInterface
{
if ($this->processor !== null) {
return $this->processor;
}
if ($this->getConfig('fileProcessor') instanceof ProcessorInterface) {
$this->processor = $this->getConfig('fileProcessor');
}
if ($this->processor === null) {
throw new RuntimeException('No processor found');
}
return $this->processor;
}
}