FileManagementTrait::processFiles()   B
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 43
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 6
eloc 21
c 1
b 0
f 1
nc 8
nop 0
dl 0
loc 43
ccs 0
cts 27
cp 0
crap 42
rs 8.9617
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Canvas\Traits;
6
7
use Canvas\Filesystem\Helper;
8
use Canvas\Http\Exception\UnprocessableEntityException;
9
use Canvas\Models\FileSystem;
10
use Canvas\Models\FileSystemEntities;
11
use Canvas\Models\FileSystemSettings;
12
use Phalcon\Http\Response;
0 ignored issues
show
Bug introduced by
The type Phalcon\Http\Response was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use Phalcon\Validation;
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use Phalcon\Validation\Validator\File as FileValidator;
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\File was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
16
/**
17
 * Trait ResponseTrait.
18
 *
19
 * @package Canvas\Traits
20
 *
21
 * @property Users $user
22
 * @property AppsPlans $appPlan
23
 * @property CompanyBranches $branches
24
 * @property Companies $company
25
 * @property UserCompanyApps $app
26
 * @property \Phalcon\Di $di
27
 *
28
 */
29
trait FileManagementTrait
30
{
31
    /**
32
     * Add a new item.
33
     *
34
     * @method POST
35
     * url /v1/filesystem
36
     *
37
     * @return \Phalcon\Http\Response
38
     *
39
     * @throws Exception
40
     */
41
    public function create() : Response
42
    {
43
        if (!$this->request->hasFiles()) {
44
            /**
45
             * @todo handle file hash to avoid uploading same files again
46
             */
47
        }
48
49
        return $this->response($this->processFiles());
50
    }
51
52
    /**
53
     * Update an item.
54
     *
55
     * @method PUT
56
     * url /v1/filesystem/{id}
57
     *
58
     * @param mixed $id
59
     *
60
     * @return \Phalcon\Http\Response
61
     *
62
     * @throws Exception
63
     */
64
    public function edit($id) : Response
65
    {
66
        $file = FileSystem::getById($id);
67
68
        $request = $this->request->getPutData();
69
70
        $systemModule = $request['system_modules_id'] ?? 0;
71
        $entityId = $request['entity_id'] ?? 0;
72
        $fieldName = $request['field_name'] ?? '';
73
74
        //associate
75
        $fileSystemEntities = new FileSystemEntities();
76
        $fileSystemEntities->filesystem_id = $file->getId();
77
        $fileSystemEntities->entity_id = $entityId;
78
        $fileSystemEntities->companies_id = $file->companies_id;
79
        $fileSystemEntities->system_modules_id = $systemModule;
80
        $fileSystemEntities->field_name = $fieldName;
81
        $fileSystemEntities->saveOrFail();
82
83
        $file->updateOrFail($request, $this->updateFields);
84
85
        return $this->response($file);
86
    }
87
88
    /**
89
     * Update a filesystem Entity,  field name.
90
     *
91
     * @param int $id
92
     *
93
     * @return Response
94
     */
95
    public function editEntity(int $id) : Response
96
    {
97
        $fileEntity = FileSystemEntities::getById($id);
98
        $request = $this->request->getPutData();
99
100
        $fileEntity->field_name = $request['field_name'];
101
        $fileEntity->updateOrFail();
102
103
        return $this->response($fileEntity);
104
    }
105
106
    /**
107
     * Delete a file atribute.
108
     *
109
     * @param $id
110
     * @param string $name
111
     *
112
     * @return void
113
     */
114
    public function deleteAttributes($id, string $name) : Response
115
    {
116
        $records = FileSystem::findFirstOrFail($id);
117
118
        $recordAttributes = FileSystemSettings::findFirstOrFail([
119
            'conditions' => 'filesystem_id = ?0 and name = ?1',
120
            'bind' => [$records->getId(), $name]
121
        ]);
122
123
        //true true delete
124
        $recordAttributes->delete();
125
126
        return $this->response(['Delete Successfully']);
127
    }
128
129
    /**
130
     * Set the validation for the files.
131
     *
132
     * @return Validation
133
     */
134
    protected function validation() : Validation
135
    {
136
        $validator = new Validation();
137
138
        /**
139
         * @todo add validation for other file types, but we need to
140
         * look for a scalable way
141
         */
142
        $uploadConfig = [
143
            'maxSize' => '100M',
144
            'messageSize' => ':field exceeds the max filesize (:max)',
145
            'allowedTypes' => [
146
                'image/jpeg',
147
                'image/png',
148
                'image/webp',
149
                'audio/mpeg',
150
                'audio/mp3',
151
                'audio/mpeg',
152
                'application/pdf',
153
                'audio/mpeg3',
154
                'audio/x-mpeg-3',
155
                'application/x-zip-compressed',
156
                'application/octet-stream',
157
                'application/msword',
158
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
159
            ],
160
            'messageType' => 'Allowed file types are :types',
161
        ];
162
163
        $validator->add(
164
            'file',
165
            new FileValidator($uploadConfig)
166
        );
167
168
        return $validator;
169
    }
170
171
    /**
172
     * Upload the document and save them to the filesystem.
173
     *
174
     * @todo add test
175
     *
176
     * @return array
177
     */
178
    protected function processFiles() : array
179
    {
180
        $allFields = $this->request->getPostData();
181
182
        $validator = $this->validation();
183
184
        $files = [];
185
        foreach ($this->request->getUploadedFiles() as $file) {
186
            //validate this current file
187
            $errors = $validator->validate([
188
                'file' => [
189
                    'name' => $file->getName(),
190
                    'type' => $file->getType(),
191
                    'tmp_name' => $file->getTempName(),
192
                    'error' => $file->getError(),
193
                    'size' => $file->getSize(),
194
                ]
195
            ]);
196
197
            /**
198
             * @todo figure out why this failes
199
             */
200
            if (!defined('API_TESTS')) {
201
                if (count($errors)) {
202
                    foreach ($errors as $error) {
203
                        throw new UnprocessableEntityException((string) $error);
204
                    }
205
                }
206
            }
207
208
            $fileSystem = Helper::upload($file);
209
210
            //add settings
211
            foreach ($allFields as $key => $settings) {
212
                $fileSystem->set($key, $settings);
213
            }
214
215
            Helper::setImageDimensions($file, $fileSystem);
216
217
            $files[] = $fileSystem;
218
        }
219
220
        return $files;
221
    }
222
}
223