Failed Conditions
Push — master ( a3a7ec...7b7813 )
by Maximo
26s queued 12s
created

FileSystemModelTrait::getAttachmentsByName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 8
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Canvas\Traits;
6
7
use Canvas\Dto\Files;
8
use Canvas\Mapper\FileMapper;
9
use Canvas\Models\FileSystem;
10
use Canvas\Models\FileSystemEntities;
11
use Canvas\Models\FileSystemSettings;
12
use Canvas\Models\SystemModules;
13
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...
14
use RuntimeException;
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 FileSystemModelTrait
30
{
31
    public $uploadedFiles = [];
32
33
    /**
34
     * Associated the list of uploaded files to this entity.
35
     *
36
     * call on the after saves
37
     *
38
     * @return void
39
     */
40
    protected function associateFileSystem() : bool
41
    {
42
        if (!empty($this->uploadedFiles) && is_array($this->uploadedFiles)) {
43
            foreach ($this->uploadedFiles as $file) {
44
                if (!isset($file['filesystem_id'])) {
45
                    continue;
46
                }
47
48
                if ($fileSystem = FileSystem::getById($file['filesystem_id'])) {
49
                    $this->attach([[
50
                        'id' => $file['id'] ?: 0,
51
                        'file' => $fileSystem,
52
                        'field_name' => $file['field_name'] ?? ''
53
                    ]]);
54
                }
55
            }
56
        }
57
58
        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...
59
    }
60
61
    /**
62
     * Over write, because of the phalcon events.
63
     *
64
     * @param array data
65
     * @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...
66
     *
67
     * @return boolean
68
     */
69
    public function update($data = null, $whiteList = null) : bool
70
    {
71
        //associate uploaded files
72
        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
        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
     *
113
     * @return boolean
114
     */
115
    public function save($data = null, $whiteList = null) : bool
116
    {
117
        //associate uploaded files
118
        if (isset($data['files'])) {
119
            if (!empty($data['files'])) {
120
                $this->uploadedFiles = $data['files'];
121
            }
122
        }
123
124
        return parent::save($data, $whiteList);
125
    }
126
127
    /**
128
     * Delete all the files from a module.
129
     *
130
     * @return bool
131
     */
132
    public function deleteFiles() : bool
133
    {
134
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
0 ignored issues
show
Deprecated Code introduced by
The function Canvas\Models\SystemModu...stemModuleByModelName() has been deprecated: v2 ( Ignorable by Annotation )

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

134
        $systemModule = /** @scrutinizer ignore-deprecated */ SystemModules::getSystemModuleByModelName(self::class);

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...
135
136
        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

136
        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

136
        if ($files = FileSystemEntities::getAllByEntityId($this->/** @scrutinizer ignore-call */ getId(), $systemModule)) {
Loading history...
137
            $files->update([], function ($file) {
138
                $file->softDelete();
139
            });
140
        }
141
142
        return true;
143
    }
144
145
    /**
146
     * Given the ID delete the file from this entity.
147
     *
148
     * @param int $id
149
     *
150
     * @return bool
151
     */
152
    public function deleteFile(int $id)
153
    {
154
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
0 ignored issues
show
Deprecated Code introduced by
The function Canvas\Models\SystemModu...stemModuleByModelName() has been deprecated: v2 ( Ignorable by Annotation )

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

154
        $systemModule = /** @scrutinizer ignore-deprecated */ SystemModules::getSystemModuleByModelName(self::class);

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...
155
156
        $file = FileSystemEntities::findFirstOrFail([
157
            'contidions' => 'id = ?0 AND entity_id = ?1 AND system_modules_id = ?2 AND is_deleted = ?3',
158
            'bind' => [$id, $this->getId(), $systemModule->getId(), 0]
159
        ]);
160
161
        if ($file) {
162
            $file->softDelete();
163
        }
164
165
        return false;
166
    }
167
168
    /**
169
     * Given the array of files we will attch this files to the files.
170
     * [
171
     *  'file' => $file,
172
     *  'file_name' => 'dfadfa'
173
     * ];.
174
     *
175
     * @param array $files
176
     *
177
     * @return void
178
     */
179
    public function attach(array $files) : bool
180
    {
181
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
0 ignored issues
show
Deprecated Code introduced by
The function Canvas\Models\SystemModu...stemModuleByModelName() has been deprecated: v2 ( Ignorable by Annotation )

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

181
        $systemModule = /** @scrutinizer ignore-deprecated */ SystemModules::getSystemModuleByModelName(self::class);

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...
182
183
        foreach ($files as $file) {
184
            //im looking for the file inside an array
185
            if (!isset($file['file'])) {
186
                continue;
187
            }
188
189
            if (!$file['file'] instanceof FileSystem) {
190
                throw new RuntimeException('Cant attach a none Filesytem to this entity');
191
            }
192
193
            $fileSystemEntities = null;
194
            //check if we are updating the attachment
195
            if ($id = (int) $file['id']) {
196
                $fileSystemEntities = FileSystemEntities::getByIdWithSystemModule($id, $systemModule);
197
            }
198
199
            //new attachment
200
            if (!is_object($fileSystemEntities)) {
201
                $fileSystemEntities = new FileSystemEntities();
202
                $fileSystemEntities->system_modules_id = $systemModule->getId();
203
                $fileSystemEntities->companies_id = $file['file']->companies_id;
204
                $fileSystemEntities->entity_id = $this->getId();
205
                $fileSystemEntities->created_at = $file['file']->created_at;
206
            }
207
208
            $fileSystemEntities->filesystem_id = $file['file']->getId();
209
            $fileSystemEntities->field_name = $file['field_name'] ?? null;
210
            $fileSystemEntities->is_deleted = 0;
211
            $fileSystemEntities->saveOrFail();
212
213
            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...
214
                $file['file']->move($this->filesNewAttachedPath());
215
            }
216
        }
217
218
        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...
219
    }
220
221
    /**
222
     * Overwrite the relationship of the filesystem to return the attachment structure
223
     * to the given user.
224
     *
225
     * @deprecated version 0.2
226
     *
227
     * @return array
228
     */
229
    public function getFilesystem() : array
230
    {
231
        return $this->getFiles();
232
    }
233
234
    /**
235
     * Overwrite the relationship of the filesystem to return the attachment structure
236
     * to the given user.
237
     *
238
     * @return array
239
     */
240
    public function getFiles(string $fileType = null) : array
241
    {
242
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
0 ignored issues
show
Deprecated Code introduced by
The function Canvas\Models\SystemModu...stemModuleByModelName() has been deprecated: v2 ( Ignorable by Annotation )

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

242
        $systemModule = /** @scrutinizer ignore-deprecated */ SystemModules::getSystemModuleByModelName(self::class);

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...
243
244
        $attachments = $this->getAttachments($fileType);
245
246
        $fileMapper = new FileMapper($this->getId(), $systemModule->getId());
247
248
        //add a mapper
249
        $this->di->getDtoConfig()
250
            ->registerMapping(FileSystemEntities::class, Files::class)
251
            ->useCustomMapper($fileMapper);
252
253
        return $this->di->getMapper()->mapMultiple($attachments, Files::class);
254
    }
255
256
    /**
257
     * Get all the files matching the field name.
258
     *
259
     * @param string $fieldName
260
     *
261
     * @return array
262
     */
263
    public function getFilesByName(string $fieldName) : array
264
    {
265
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
0 ignored issues
show
Deprecated Code introduced by
The function Canvas\Models\SystemModu...stemModuleByModelName() has been deprecated: v2 ( Ignorable by Annotation )

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

265
        $systemModule = /** @scrutinizer ignore-deprecated */ SystemModules::getSystemModuleByModelName(self::class);

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...
266
267
        $attachments = $this->getAttachmentsByName($fieldName);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $attachments is correct as $this->getAttachmentsByName($fieldName) targeting Canvas\Traits\FileSystem...:getAttachmentsByName() 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...
268
269
        $fileMapper = new FileMapper($this->getId(), $systemModule->getId());
270
271
        //add a mapper
272
        $this->di->getDtoConfig()
273
            ->registerMapping(FileSystemEntities::class, Files::class)
274
            ->useCustomMapper($fileMapper);
275
276
        return $this->di->getMapper()->mapMultiple($attachments, Files::class);
277
    }
278
279
    /**
280
     * Get a file by its fieldname.
281
     *
282
     * @todo this will be a performance issue in the future look for better ways to handle this
283
     * when a company has over 1k images
284
     *
285
     * @param string $name
286
     *
287
     * @return void
288
     */
289
    public function getAttachmentByName(string $fieldName)
290
    {
291
        $criteria = $this->searchCriteriaForFilesByName($fieldName);
292
293
        return FileSystemEntities::findFirst([
294
            'conditions' => $criteria['conditions'],
295
            'order' => 'id desc',
296
            'bind' => $criteria['bind'],
297
        ]);
298
    }
299
300
    /**
301
     * Get a files by its fieldname.
302
     *
303
     * @param string $name
304
     *
305
     * @return void
306
     */
307
    public function getAttachmentsByName(string $fieldName)
308
    {
309
        $criteria = $this->searchCriteriaForFilesByName($fieldName);
310
311
        return FileSystemEntities::find([
312
            'conditions' => $criteria['conditions'],
313
            'order' => 'id desc',
314
            'bind' => $criteria['bind'],
315
        ]);
316
    }
317
318
    /**
319
     * Get the file byt it's name.
320
     *
321
     * @param string $fieldName
322
     *
323
     * @return string|null
324
     */
325
    public function getFileByName(string $fieldName) : ?object
326
    {
327
        return $this->fileMapper($this->getAttachmentByName($fieldName));
0 ignored issues
show
Bug introduced by
$this->getAttachmentByName($fieldName) of type void is incompatible with the type Canvas\Models\FileSystemEntities|null expected by parameter $fileEntity of Canvas\Traits\FileSystemModelTrait::fileMapper(). ( Ignorable by Annotation )

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

327
        return $this->fileMapper(/** @scrutinizer ignore-type */ $this->getAttachmentByName($fieldName));
Loading history...
Bug Best Practice introduced by
The expression return $this->fileMapper...mentByName($fieldName)) also could return the type object which is incompatible with the documented return type null|string.
Loading history...
Bug introduced by
Are you sure the usage of $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 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...
328
    }
329
330
    /**
331
     * Get file by name and attributes.
332
     *
333
     * @param string $fieldName
334
     * @param string $key
335
     * @param string $value
336
     *
337
     * @return object|null
338
     */
339
    public function getFileByNameWithAttributes(string $fieldName, string $key, string $value) : ?object
340
    {
341
        return $this->fileMapper($this->getAttachmentByNameAndAttributes($fieldName, $key, $value));
0 ignored issues
show
Bug introduced by
$this->getAttachmentByNa...ieldName, $key, $value) of type void is incompatible with the type Canvas\Models\FileSystemEntities|null expected by parameter $fileEntity of Canvas\Traits\FileSystemModelTrait::fileMapper(). ( Ignorable by Annotation )

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

341
        return $this->fileMapper(/** @scrutinizer ignore-type */ $this->getAttachmentByNameAndAttributes($fieldName, $key, $value));
Loading history...
Bug introduced by
Are you sure the usage of $this->getAttachmentByNa...ieldName, $key, $value) targeting Canvas\Traits\FileSystem...ntByNameAndAttributes() 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...
342
    }
343
344
    /**
345
     * Convert identity to mapper.
346
     *
347
     * @param FileSystemEntities|null $fileEntity
348
     *
349
     * @return object|null
350
     */
351
    protected function fileMapper($fileEntity) : ?object
352
    {
353
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
0 ignored issues
show
Deprecated Code introduced by
The function Canvas\Models\SystemModu...stemModuleByModelName() has been deprecated: v2 ( Ignorable by Annotation )

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

353
        $systemModule = /** @scrutinizer ignore-deprecated */ SystemModules::getSystemModuleByModelName(self::class);

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...
354
355
        if ($fileEntity instanceof FileSystemEntities) {
356
            $fileMapper = new FileMapper($this->getId(), $systemModule->getId());
357
358
            //add a mapper
359
            $this->di->getDtoConfig()
360
                ->registerMapping(FileSystemEntities::class, Files::class)
361
                ->useCustomMapper($fileMapper);
362
363
            /**
364
             * @todo create a mapper for entity so we dont have to look for the relationship?
365
             */
366
            return $this->di->getMapper()->map($fileEntity, Files::class);
367
        }
368
369
        return null;
370
    }
371
372
    /**
373
     * Given this entity define a new path.
374
     *
375
     * @param string $path
376
     *
377
     * @return string
378
     */
379
    protected function filesNewAttachedPath() : ?string
380
    {
381
        return null;
382
    }
383
384
    /**
385
     * Search Criteria for file by name.
386
     *
387
     * @param string $fieldName
388
     *
389
     * @return array
390
     */
391
    protected function searchCriteriaForFilesByName(string $fieldName) : array
392
    {
393
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
0 ignored issues
show
Deprecated Code introduced by
The function Canvas\Models\SystemModu...stemModuleByModelName() has been deprecated: v2 ( Ignorable by Annotation )

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

393
        $systemModule = /** @scrutinizer ignore-deprecated */ SystemModules::getSystemModuleByModelName(self::class);

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...
394
        $appPublicImages = (bool) $this->di->getApp()->get('public_images');
395
396
        $bindParams = [
397
            'system_module_id' => $systemModule->getId(),
398
            'entity_id' => $this->getId(),
399
            'is_deleted' => 0,
400
            'field_name' => $fieldName,
401
        ];
402
403
        //do we allow images by entity to be public to anybody accessing it directly by the entity?
404
        if ($appPublicImages) {
405
            $condition = 'system_modules_id = :system_module_id: AND entity_id = :entity_id: AND is_deleted = :is_deleted: and field_name = :field_name: ';
406
        } else {
407
            $bindParams['company_id'] = $this->di->getUserData()->currentCompanyId();
408
            $condition = 'system_modules_id = :system_module_id: AND entity_id = :entity_id: AND is_deleted = :is_deleted: and field_name = :field_name: and companies_id = :company_id:';
409
        }
410
411
        return [
412
            'bind' => $bindParams,
413
            'conditions' => $condition
414
        ];
415
    }
416
417
    /**
418
     * Given the filename look for it version with
419
     * the key and value associated to the file.
420
     *
421
     * @param string $fieldName
422
     * @param string $key
423
     * @param string $value
424
     *
425
     * @return void
426
     */
427
    public function getAttachmentByNameAndAttributes(string $fieldName, string $key, string $value)
428
    {
429
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
0 ignored issues
show
Deprecated Code introduced by
The function Canvas\Models\SystemModu...stemModuleByModelName() has been deprecated: v2 ( Ignorable by Annotation )

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

429
        $systemModule = /** @scrutinizer ignore-deprecated */ SystemModules::getSystemModuleByModelName(self::class);

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...
430
        $appPublicImages = (bool) $this->di->getApp()->get('public_images');
431
432
        $bindParams = [
433
            'system_module_id' => $systemModule->getId(),
434
            'entity_id' => $this->getId(),
435
            'is_deleted' => 0,
436
            'field_name' => $fieldName,
437
            'name' => $key,
438
            'value' => $value
439
        ];
440
441
        //do we allow images by entity to be public to anybody accessing it directly by the entity?
442
        if ($appPublicImages) {
443
            $condition = 'system_modules_id = :system_module_id: AND entity_id = :entity_id: AND is_deleted = :is_deleted: and field_name = :field_name: 
444
            AND filesystem_id IN (
445
                SELECT s.filesystem_id FROM 
446
                    ' . FileSystemSettings::class . ' s 
447
                    WHERE name = :name: AND value = :value: 
448
            )';
449
        } else {
450
            $bindParams['company_id'] = $this->di->getUserData()->currentCompanyId();
451
            $condition = 'system_modules_id = :system_module_id: AND entity_id = :entity_id: AND is_deleted = :is_deleted: and field_name = :field_name: and companies_id = :company_id: 
452
            AND filesystem_id IN (
453
                SELECT s.filesystem_id FROM 
454
                    ' . FileSystemSettings::class . ' s 
455
                    WHERE name = :name: AND value = :value: 
456
            )';
457
        }
458
459
        return FileSystemEntities::findFirst([
460
            'conditions' => $condition,
461
            'order' => 'id desc',
462
            'bind' => $bindParams
463
        ]);
464
    }
465
466
    /**
467
     * Get all the files attach for the given module.
468
     *
469
     * @param string $fileType filter the files by their type
470
     *
471
     * @return array
472
     */
473
    public function getAttachments(string $fileType = null) : ResultsetInterface
474
    {
475
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
0 ignored issues
show
Deprecated Code introduced by
The function Canvas\Models\SystemModu...stemModuleByModelName() has been deprecated: v2 ( Ignorable by Annotation )

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

475
        $systemModule = /** @scrutinizer ignore-deprecated */ SystemModules::getSystemModuleByModelName(self::class);

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...
476
        $appPublicImages = (bool) $this->di->getApp()->get('public_images');
477
478
        $bindParams = [
479
            'system_module_id' => $systemModule->getId(),
480
            'entity_id' => $this->getId(),
481
            'is_deleted' => 0,
482
        ];
483
484
        /**
485
         * We can also filter the attachments by its file type.
486
         */
487
        $fileTypeSql = null;
488
        if ($fileType) {
489
            $fileTypeSql = !is_null($fileType) ? 'AND f.file_type = :file_type:' : null;
0 ignored issues
show
introduced by
The condition is_null($fileType) is always false.
Loading history...
490
            $bindParams['file_type'] = $fileType;
491
        }
492
493
        //do we allow images by entity to be public to anybody accessing it directly by the entity?
494
        if ($appPublicImages) {
495
            /**
496
             * @todo optimize this queries to slow
497
             */
498
            $condition = 'system_modules_id = :system_module_id: AND entity_id = :entity_id: AND is_deleted = :is_deleted:
499
            AND filesystem_id IN (SELECT f.id from \Canvas\Models\FileSystem f WHERE
500
                f.is_deleted = :is_deleted: ' . $fileTypeSql . '
501
            )';
502
        } else {
503
            $bindParams['company_id'] = $this->di->getUserData()->currentCompanyId();
504
505
            $condition = 'system_modules_id = :system_module_id: AND entity_id = :entity_id: AND is_deleted = :is_deleted: and companies_id = :company_id:
506
            AND filesystem_id IN (SELECT f.id from \Canvas\Models\FileSystem f WHERE
507
                f.is_deleted = :is_deleted: AND f.companies_id = :company_id: ' . $fileTypeSql . '
508
            )';
509
        }
510
511
        return FileSystemEntities::find([
512
            'conditions' => $condition,
513
            'order' => 'id desc',
514
            'bind' => $bindParams
515
        ]);
516
    }
517
}
518