Test Failed
Pull Request — master (#90)
by Maximo
07:11
created

FileManagementTrait::createUppy()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 9
ccs 0
cts 7
cp 0
crap 6
rs 10
c 0
b 0
f 0
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::findFirstOrFail($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->system_modules_id = $systemModule;
103
        $fileSystemEntities->field_name = $fieldName;
104
        $fileSystemEntities->saveOrFail();
105
106
        $file->updateOrFail($request, $this->updateFields);
107
108
        return $this->response($file);
109
    }
110
111
    /**
112
     * Delete a file atribute.
113
     *
114
     * @param $id
115
     * @param string $name
116
     * @return void
117
     */
118
    public function deleteAttributes($id, string $name): Response
119
    {
120
        $records = FileSystem::findFirstOrFail($id);
121
122
        $recordAttributes = FileSystemSettings::findFirstOrFail([
123
            'conditions' => 'filesystem_id = ?0 and name = ?1',
124
            'bind' => [$records->getId(), $name]
125
        ]);
126
127
        //true true delete
128
        $recordAttributes->delete();
129
130
        return $this->response(['Delete Successfully']);
131
    }
132
133
    /**
134
     * Set the validation for the files.
135
     *
136
     * @return Validation
137
     */
138
    protected function validation(): Validation
139
    {
140
        $validator = new Validation();
141
142
        /**
143
         * @todo add validation for other file types, but we need to
144
         * look for a scalable way
145
         */
146
        $uploadConfig = [
147
            'maxSize' => '100M',
148
            'messageSize' => ':field exceeds the max filesize (:max)',
149
            'allowedTypes' => [
150
                'image/jpeg',
151
                'image/png',
152
                'audio/mpeg',
153
                'audio/mp3',
154
                'audio/mpeg',
155
                'application/pdf',
156
                'audio/mpeg3',
157
                'audio/x-mpeg-3',
158
                'application/x-zip-compressed',
159
                'application/octet-stream',
160
            ],
161
            'messageType' => 'Allowed file types are :types',
162
        ];
163
164
        $validator->add(
165
            'file',
166
            new FileValidator($uploadConfig)
167
        );
168
169
        return $validator;
170
    }
171
172
    /**
173
     * Upload the document and save them to the filesystem.
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(['file' => [
188
                'name' => $file->getName(),
189
                'type' => $file->getType(),
190
                'tmp_name' => $file->getTempName(),
191
                'error' => $file->getError(),
192
                'size' => $file->getSize(),
193
            ]]);
194
195
            /**
196
             * @todo figure out why this failes
197
             */
198
            if (!defined('API_TESTS')) {
199
                if (count($errors)) {
200
                    foreach ($errors as $error) {
201
                        throw new UnprocessableEntityHttpException((string)$error);
202
                    }
203
                }
204
            }
205
206
            //get the filesystem config
207
            $appSettingFileConfig = $this->di->get('app')->get('filesystem');
208
            $fileSystemConfig = $this->config->filesystem->{$appSettingFileConfig};
209
210
            //create local filesystem , for temp files
211
            $this->di->get('filesystem', ['local'])->createDir($this->config->filesystem->local->path);
212
213
            //get the tem file
214
            $filePath = Helper::generateUniqueName($file, $this->config->filesystem->local->path);
215
            $compleFilePath = $fileSystemConfig->path . $filePath;
216
            $uploadFileNameWithPath = $appSettingFileConfig == 'local' ? $filePath : $compleFilePath;
217
218
            /**
219
             * upload file base on temp.
220
             * @todo change this to determine type of file and recreate it if its a image
221
             */
222
            $this->di->get('filesystem')->writeStream($uploadFileNameWithPath, fopen($file->getTempName(), 'r'));
223
224
            $fileSystem = new FileSystem();
225
            $fileSystem->name = $file->getName();
226
            $fileSystem->companies_id = $this->userData->currentCompanyId();
227
            $fileSystem->apps_id = $this->app->getId();
228
            $fileSystem->users_id = $this->userData->getId();
229
            $fileSystem->path = $compleFilePath;
230
            $fileSystem->url = $fileSystemConfig->cdn . DIRECTORY_SEPARATOR . $uploadFileNameWithPath;
231
            $fileSystem->file_type = $file->getExtension();
232
            $fileSystem->size = $file->getSize();
233
234
            $fileSystem->saveOrFail();
235
236
            //add settings
237
            foreach ($allFields as $key => $settings) {
238
                $fileSystem->set($key, $settings);
239
            }
240
241
            $files[] = $fileSystem;
242
        }
243
244
        return $files;
245
    }
246
}
247