Test Failed
Pull Request — master (#135)
by Rafael
11:13
created

FileSystemModelTrait::getAttachmentByName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Canvas\Traits;
6
7
use Canvas\Models\SystemModules;
8
use Canvas\Models\FileSystem;
9
use RuntimeException;
10
use Phalcon\Mvc\Model\Resultset\Simple;
0 ignored issues
show
Bug introduced by
The type Phalcon\Mvc\Model\Resultset\Simple 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...
11
use Canvas\Models\FileSystemEntities;
12
use Canvas\Dto\Files;
13
use Canvas\Mapper\FileMapper;
14
use Phalcon\Di;
15
use Phalcon\Mvc\Model\ResultsetInterface;
0 ignored issues
show
Bug introduced by
The type Phalcon\Mvc\Model\ResultsetInterface 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...
16
17
/**
18
 * Trait ResponseTrait.
19
 *
20
 * @package Canvas\Traits
21
 *
22
 * @property Users $user
23
 * @property AppsPlans $appPlan
24
 * @property CompanyBranches $branches
25
 * @property Companies $company
26
 * @property UserCompanyApps $app
27
 * @property \Phalcon\Di $di
28
 *
29
 */
30
trait FileSystemModelTrait
31
{
32
    public $uploadedFiles = [];
33
34
    /**
35
     * Associated the list of uploaded files to this entity.
36
     *
37
     * call on the after saves
38
     *
39
     * @return void
40
     */
41 3
    protected function associateFileSystem(): bool
42
    {
43 3
        if (!empty($this->uploadedFiles) && is_array($this->uploadedFiles)) {
44
            foreach ($this->uploadedFiles as $file) {
45
                if (!isset($file['filesystem_id'])) {
46
                    continue;
47
                }
48
49
                if ($fileSystem = FileSystem::getById($file['filesystem_id'])) {
50
                    $this->attach([[
51
                        'id' => $file['id'] ?: 0,
52
                        'file' => $fileSystem,
53
                        'field_name' => $file['field_name'] ?? ''
54
                    ]]);
55
                }
56
            }
57
        }
58
59 3
        return true;
0 ignored issues
show
Bug Best Practice introduced by
The expression return true returns the type true which is incompatible with the documented return type void.
Loading history...
60
    }
61
62
    /**
63
     * Over write, because of the phalcon events.
64
     *
65
     * @param array data
66
     * @param array whiteList
0 ignored issues
show
Bug introduced by
The type Canvas\Traits\whiteList 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...
67
     * @return boolean
68
     */
69 1
    public function update($data = null, $whiteList = null): bool
70
    {
71
        //associate uploaded files
72 1
        if (isset($data['files'])) {
73
            if (!empty($data['files'])) {
74
                /**
75
                 * @todo for now lets delete them all and updated them
76
                 * look for a better solution later, this can since we are not using transactions
77
                 */
78
                $this->deleteFiles();
79
80
                $this->uploadedFiles = $data['files'];
81
            } else {
82
                $this->deleteFiles();
83
            }
84
        }
85
86 1
        return parent::update($data, $whiteList);
87
    }
88
89
    /**
90
     * Inserts or updates a model instance. Returning true on success or false otherwise.
91
     *
92
     *<code>
93
     * // Creating a new robot
94
     * $robot = new Robots();
95
     *
96
     * $robot->type = "mechanical";
97
     * $robot->name = "Astro Boy";
98
     * $robot->year = 1952;
99
     *
100
     * $robot->save();
101
     *
102
     * // Updating a robot name
103
     * $robot = Robots::findFirst("id = 100");
104
     *
105
     * $robot->name = "Biomass";
106
     *
107
     * $robot->save();
108
     *</code>
109
     *
110
     * @param array data
111
     * @param array whiteList
112
     * @return boolean
113
     */
114 3
    public function save($data = null, $whiteList = null): bool
115
    {
116
        //associate uploaded files
117 3
        if (isset($data['files'])) {
118
            if (!empty($data['files'])) {
119
                $this->uploadedFiles = $data['files'];
120
            }
121
        }
122
123 3
        return parent::save($data, $whiteList);
124
    }
125
126
    /**
127
     * Delete all the files from a module.
128
     *
129
     * @return bool
130
     */
131
    public function deleteFiles(): bool
132
    {
133
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
134
135
        if ($files = FileSystemEntities::getAllByEntityId($this->getId(), $systemModule)) {
0 ignored issues
show
Unused Code introduced by
The call to Canvas\Models\FileSystem...ies::getAllByEntityId() has too many arguments starting with $systemModule. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

135
        if ($files = FileSystemEntities::/** @scrutinizer ignore-call */ getAllByEntityId($this->getId(), $systemModule)) {

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
Bug introduced by
It seems like getId() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

135
        if ($files = FileSystemEntities::getAllByEntityId($this->/** @scrutinizer ignore-call */ getId(), $systemModule)) {
Loading history...
136
            $files->update([], function ($file) {
137
                $file->softDelete();
138
            });
139
        }
140
141
        return true;
142
    }
143
144
    /**
145
     * Given the ID delete the file from this entity.
146
     *
147
     * @param integer $id
148
     * @return bool
149
     */
150
    public function deleteFile(int $id)
151
    {
152
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
153
154
        $file = FileSystemEntities::findFirstOrFail([
155
            'contidions' => 'id = ?0 AND entity_id = ?1 AND system_modules_id = ?2 AND is_deleted = ?3',
156
            'bind' => [$id, $this->getId(), $systemModule->getId(), 0]
157
        ]);
158
159
        if ($file) {
0 ignored issues
show
introduced by
$file is of type Baka\Database\Model, thus it always evaluated to true.
Loading history...
160
            $file->softDelete();
161
        }
162
163
        return false;
164
    }
165
166
    /**
167
     * Given the array of files we will attch this files to the files.
168
     * [
169
     *  'file' => $file,
170
     *  'file_name' => 'dfadfa'
171
     * ];.
172
     *
173
     * @param array $files
174
     * @return void
175
     */
176
    public function attach(array $files): bool
177
    {
178
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
179
180
        foreach ($files as $file) {
181
            //im looking for the file inside an array
182
            if (!array_key_exists('file', $file)) {
183
                continue;
184
            }
185
186
            if (!$file['file'] instanceof FileSystem) {
187
                throw new RuntimeException('Cant attach a none Filesytem to this entity');
188
            }
189
190
            $fileSystemEntities = null;
191
            //check if we are updating the attachment
192
            if ($id = (int) $file['id']) {
193
                $fileSystemEntities = FileSystemEntities::getByIdWithSystemModule($id, $systemModule, true);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $fileSystemEntities is correct as Canvas\Models\FileSystem...d, $systemModule, true) targeting Canvas\Models\FileSystem...tByIdWithSystemModule() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
194
            }
195
196
            //new attachment
197
            if (!is_object($fileSystemEntities)) {
198
                $fileSystemEntities = new FileSystemEntities();
199
                $fileSystemEntities->system_modules_id = $systemModule->getId();
200
                $fileSystemEntities->companies_id = $file['file']->companies_id;
201
                $fileSystemEntities->entity_id = $this->getId();
202
                $fileSystemEntities->created_at = $file['file']->created_at;
203
            }
204
205
            $fileSystemEntities->filesystem_id = $file['file']->getId();
206
            $fileSystemEntities->field_name = $file['field_name'] ?? null;
207
            $fileSystemEntities->is_deleted = 0;
208
            $fileSystemEntities->saveOrFail();
209
210
            if (!is_null($this->filesNewAttachedPath())) {
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->filesNewAttachedPath() targeting Canvas\Traits\FileSystem...:filesNewAttachedPath() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
211
                $file['file']->move($this->filesNewAttachedPath());
212
            }
213
        }
214
215
        return true;
0 ignored issues
show
Bug Best Practice introduced by
The expression return true returns the type true which is incompatible with the documented return type void.
Loading history...
216
    }
217
218
    /**
219
     * Get all the files attach for the given module.
220
     *
221
     * @param string $fileType filter the files by their type
222
     * @return array
223
     */
224
    public function getAttachments(string $fileType = null) : ResultsetInterface
225
    {
226
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
227
        $companyId = $this->di->getUserData()->currentCompanyId();
228
229
        $bindParams = [
230
            $systemModule->getId(),
231
            $this->getId(),
232
            0,
233
            $companyId
234
        ];
235
236
        /**
237
         * We can also filter the attachements by its file type.
238
         */
239
        $fileTypeSql = !is_null($fileType) ? 'AND f.file_type = ?4' : null;
240
        if ($fileTypeSql) {
241
            $bindParams[] = $fileType;
242
        }
243
244
        return FileSystemEntities::find([
245
            'conditions' => 'system_modules_id = ?0 AND entity_id = ?1 AND is_deleted = ?2 and companies_id = ?3
246
                            AND filesystem_id IN (SELECT f.id from \Canvas\Models\FileSystem f WHERE
247
                                f.is_deleted = ?2 AND f.companies_id = ?3 ' . $fileTypeSql . '
248
                            )',
249
            'bind' => $bindParams
250
        ]);
251
    }
252
253
    /**
254
     * Overwrite the relationship of the filesystem to return the attachment structure
255
     * to the given user.
256
     *
257
     * @deprecated version 0.2
258
     * @return array
259
     */
260
    public function getFilesystem(): array
261
    {
262
        return $this->getFiles();
263
    }
264
265
    /**
266
     * Overwrite the relationship of the filesystem to return the attachment structure
267
     * to the given user.
268
     *
269
     * @return array
270
     */
271
    public function getFiles(string $fileType = null): array
272
    {
273
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
274
275
        $attachments = $this->getAttachments($fileType);
276
277
        $fileMapper = new FileMapper($this->getId(), $systemModule->getId());
278
279
        //add a mapper
280
        $this->di->getDtoConfig()->registerMapping(FileSystemEntities::class, Files::class)
281
            ->useCustomMapper($fileMapper);
282
283
        return $this->di->getMapper()->mapMultiple($attachments, Files::class);
284
    }
285
286
    /**
287
     * Get a file by its fieldname.
288
     *
289
     * @todo this will be a performance issue in the futur look for better ways to handle this
290
     * when a company has over 1k images
291
     *
292
     * @deprecated version 0.2
293
     * @param string $name
294
     * @return void
295
     */
296 1
    public function getAttachmentByName(string $fieldName)
297
    {
298 1
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
299 1
        $companyId = $this->di->getUserData()->currentCompanyId();
300
301 1
        return FileSystemEntities::findFirst([
302 1
            'conditions' => 'system_modules_id = ?0 AND entity_id = ?1 AND is_deleted = ?2 and field_name = ?3 and companies_id = ?4
303
                            AND filesystem_id IN (SELECT f.id from \Canvas\Models\FileSystem f WHERE
304
                                f.is_deleted = ?2 AND f.companies_id = ?4
305
                            )',
306 1
            'bind' => [$systemModule->getId(), $this->getId(), 0, $fieldName, $companyId]
307
        ]);
308
    }
309
310
    /**
311
     * Undocumented function.
312
     *
313
     * @param string $fieldName
314
     * @return string|null
315
     */
316 1
    public function getFileByName(string $fieldName): ?object
317
    {
318 1
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
319
320 1
        $fileEntity = $this->getAttachmentByName($fieldName);
0 ignored issues
show
Deprecated Code introduced by
The function Canvas\Traits\FileSystem...::getAttachmentByName() has been deprecated: version 0.2 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

320
        $fileEntity = /** @scrutinizer ignore-deprecated */ $this->getAttachmentByName($fieldName);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
Bug introduced by
Are you sure the assignment to $fileEntity is correct as $this->getAttachmentByName($fieldName) targeting Canvas\Traits\FileSystem...::getAttachmentByName() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
321
322 1
        if ($fileEntity) {
0 ignored issues
show
introduced by
$fileEntity is of type void, thus it always evaluated to false.
Loading history...
323 1
            $fileMapper = new FileMapper($this->getId(), $systemModule->getId());
324
325
            //add a mapper
326 1
            $this->di->getDtoConfig()->registerMapping(FileSystemEntities::class, Files::class)
327 1
                ->useCustomMapper($fileMapper);
328
329
            /**
330
             * @todo create a mapper for entity so we dont have to look for the relationship?
331
             */
332 1
            return $this->di->getMapper()->map($fileEntity, Files::class);
333
        }
334
335
        return null;
336
    }
337
338
    /**
339
     * Given this entity define a new path.
340
     *
341
     * @param string $path
342
     * @return string
343
     */
344
    protected function filesNewAttachedPath(): ?string
345
    {
346
        return null;
347
    }
348
}
349