-
Notifications
You must be signed in to change notification settings - Fork 250
Expand file tree
/
Copy pathUploadBehavior.php
More file actions
287 lines (260 loc) · 10.9 KB
/
Copy pathUploadBehavior.php
File metadata and controls
287 lines (260 loc) · 10.9 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
<?php
namespace Josegonzalez\Upload\Model\Behavior;
use ArrayObject;
use Cake\Collection\Collection;
use Cake\Database\Type;
use Cake\Event\Event;
use Cake\ORM\Behavior;
use Cake\ORM\Entity;
use Cake\Utility\Hash;
use Exception;
use Josegonzalez\Upload\File\Path\DefaultProcessor;
use Josegonzalez\Upload\File\Transformer\DefaultTransformer;
use Josegonzalez\Upload\File\Writer\DefaultWriter;
use UnexpectedValueException;
class UploadBehavior extends Behavior
{
private $protectedFieldNames = [
'priority',
];
/**
* Initialize hook
*
* @param array $config The config for this behavior.
* @return void
*/
public function initialize(array $config)
{
$configs = [];
foreach ($config as $field => $settings) {
if (is_int($field)) {
$configs[$settings] = [];
} else {
$configs[$field] = $settings;
}
}
$this->setConfig($configs);
$this->setConfig('className', null);
Type::map('upload.file', 'Josegonzalez\Upload\Database\Type\FileType');
$schema = $this->_table->getSchema();
foreach (array_keys($this->getConfig()) as $field) {
$schema->setColumnType($field, 'upload.file');
}
$this->_table->setSchema($schema);
}
/**
* Modifies the data being marshalled to ensure invalid upload data is not inserted
*
* @param \Cake\Event\Event $event an event instance
* @param \ArrayObject $data data being marshalled
* @param \ArrayObject $options options for the current event
* @return void
*/
public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options)
{
$validator = $this->_table->getValidator();
$dataArray = $data->getArrayCopy();
foreach (array_keys($this->getConfig(null, [])) as $field) {
if (!$validator->isEmptyAllowed($field, false)) {
continue;
}
if (Hash::get($dataArray, $field . '.error') !== UPLOAD_ERR_NO_FILE) {
continue;
}
unset($data[$field]);
}
}
/**
* Modifies the entity before it is saved so that uploaded file data is persisted
* in the database too.
*
* @param \Cake\Event\Event $event The beforeSave event that was fired
* @param \Cake\ORM\Entity $entity The entity that is going to be saved
* @param \ArrayObject $options the options passed to the save method
* @return void|false
*/
public function beforeSave(Event $event, Entity $entity, ArrayObject $options)
{
foreach ($this->getConfig(null, []) as $field => $settings) {
if (in_array($field, $this->protectedFieldNames)) {
continue;
}
$uploadValidator = $this->getUploadValidator($entity, $settings, $field);
if ($uploadValidator->hasUploadFailed()) {
if (Hash::get($settings, 'restoreValueOnFailure', true)) {
$entity->set($field, $entity->getOriginal($field));
$entity->setDirty($field, false);
}
continue;
}
$data = $entity->get($field);
$path = $this->getPathProcessor($entity, $data, $field, $settings);
$basepath = $path->basepath();
$filename = $path->filename();
if (is_string($data)) {
$temp = [];
$temp['name'] = $filename;
$temp['data'] = $data;
$data = $temp;
} else {
$data['name'] = $filename;
}
$files = $this->constructFiles($entity, $data, $field, $settings, $basepath);
$writer = $this->getWriter($entity, $data, $field, $settings);
$success = $writer->write($files);
if ((new Collection($success))->contains(false)) {
return false;
}
$entity->set($field, $filename);
$entity->set(Hash::get($settings, 'fields.dir', 'dir'), $basepath);
if (!isset($temp)) {
$entity->set(Hash::get($settings, 'fields.size', 'size'), $data['size']);
$entity->set(Hash::get($settings, 'fields.type', 'type'), $data['type']);
}
}
}
/**
* Deletes the files after the entity is deleted
*
* @param \Cake\Event\Event $event The afterDelete event that was fired
* @param \Cake\ORM\Entity $entity The entity that was deleted
* @param \ArrayObject $options the options passed to the delete method
* @return void|false
*/
public function afterDelete(Event $event, Entity $entity, ArrayObject $options)
{
$result = true;
foreach ($this->getConfig(null, []) as $field => $settings) {
if (in_array($field, $this->protectedFieldNames) || Hash::get($settings, 'keepFilesOnDelete', true)) {
continue;
}
$dirField = Hash::get($settings, 'fields.dir', 'dir');
if ($entity->has($dirField)) {
$path = $entity->get($dirField);
} else {
$path = $this->getPathProcessor($entity, $entity->get($field), $field, $settings)->basepath();
}
$callback = Hash::get($settings, 'deleteCallback', null);
if ($callback && is_callable($callback)) {
$files = $callback($path, $entity, $field, $settings);
} else {
$files = [$path . $entity->get($field)];
}
$writer = $this->getWriter($entity, [], $field, $settings);
$success = $writer->delete($files);
if ($result && (new Collection($success))->contains(false)) {
$result = false;
}
}
return $result;
}
/**
* Retrieves an instance of a path processor which knows how to build paths
* for a given file upload
*
* @param \Cake\ORM\Entity $entity an entity
* @param array $data the data being submitted for a save
* @param string $field the field for which data will be saved
* @param array $settings the settings for the current field
* @return \Josegonzalez\Upload\File\Path\AbstractProcessor
*/
public function getPathProcessor(Entity $entity, $data, $field, $settings)
{
$default = 'Josegonzalez\Upload\File\Path\DefaultProcessor';
$processorClass = Hash::get($settings, 'pathProcessor', $default);
if (is_subclass_of($processorClass, 'Josegonzalez\Upload\File\Path\ProcessorInterface')) {
return new $processorClass($this->_table, $entity, $data, $field, $settings);
}
throw new UnexpectedValueException(sprintf(
"'pathProcessor' not set to instance of ProcessorInterface: %s",
$processorClass
));
}
/**
* Retrieves an instance of a file writer which knows how to write files to disk
*
* @param \Cake\ORM\Entity $entity an entity
* @param array $data the data being submitted for a save
* @param string $field the field for which data will be saved
* @param array $settings the settings for the current field
* @return \Josegonzalez\Upload\File\Path\AbstractProcessor
*/
public function getWriter(Entity $entity, $data, $field, $settings)
{
$default = 'Josegonzalez\Upload\File\Writer\DefaultWriter';
$writerClass = Hash::get($settings, 'writer', $default);
if (is_subclass_of($writerClass, 'Josegonzalez\Upload\File\Writer\WriterInterface')) {
return new $writerClass($this->_table, $entity, $data, $field, $settings);
}
throw new UnexpectedValueException(sprintf(
"'writer' not set to instance of WriterInterface: %s",
$writerClass
));
}
/**
* Retrieves an instance of a validator that validates that the current upload has succeded
*
* @param \Cake\ORM\Entity $entity an entity
* @param array $data the data being submitted for a save
* @return \Josegonzalez\Upload\UploadValidator\UploadValidatorInterface
*/
public function getUploadValidator(Entity $entity, $settings, $field)
{
$default = 'Josegonzalez\Upload\UploadValidator\DefaultUploadValidator';
$uploadValidatorClass = Hash::get($settings, 'uploadValidator', $default);
if (is_subclass_of($uploadValidatorClass, 'Josegonzalez\Upload\UploadValidator\UploadValidatorInterface')) {
return new $uploadValidatorClass($entity, $field);
}
throw new UnexpectedValueException(sprintf(
"'uploadValidator' not set to instance of UploadValidatorInterface: %s",
$uploadValidatorClass
));
}
/**
* Creates a set of files from the initial data and returns them as key/value
* pairs, where the path on disk maps to name which each file should have.
* This is done through an intermediate transformer, which should return
* said array. Example:
*
* [
* '/tmp/path/to/file/on/disk' => 'file.pdf',
* '/tmp/path/to/file/on/disk-2' => 'file-preview.png',
* ]
*
* A user can specify a callable in the `transformer` setting, which can be
* used to construct this key/value array. This processor can be used to
* create the source files.
*
* @param \Cake\ORM\Entity $entity an entity
* @param array $data the data being submitted for a save
* @param string $field the field for which data will be saved
* @param array $settings the settings for the current field
* @param string $basepath a basepath where the files are written to
* @return array key/value pairs of temp files mapping to their names
*/
public function constructFiles(Entity $entity, $data, $field, $settings, $basepath)
{
$basepath = (substr($basepath, -1) == DS ? $basepath : $basepath . DS);
$default = 'Josegonzalez\Upload\File\Transformer\DefaultTransformer';
$transformerClass = Hash::get($settings, 'transformer', $default);
$results = [];
if (is_subclass_of($transformerClass, 'Josegonzalez\Upload\File\Transformer\TransformerInterface')) {
$transformer = new $transformerClass($this->_table, $entity, $data, $field, $settings);
$results = $transformer->transform();
foreach ($results as $key => $value) {
$results[$key] = $basepath . $value;
}
} elseif (is_callable($transformerClass)) {
$results = $transformerClass($this->_table, $entity, $data, $field, $settings);
foreach ($results as $key => $value) {
$results[$key] = $basepath . $value;
}
} else {
throw new UnexpectedValueException(sprintf(
"'transformer' not set to instance of TransformerInterface: %s",
$transformerClass
));
}
return $results;
}
}