Test Failed
Pull Request — master (#123)
by Maximo
06:15
created

FileManagementTrait::processFiles()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 41
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

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