Test Failed
Pull Request — master (#126)
by Maximo
13:19 queued 06:57
created

FileSystemModelTrait::getAttachmentByName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 11
ccs 0
cts 10
cp 0
crap 2
rs 10
c 0
b 0
f 0
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
    protected function associateFileSystem(): bool
42
    {
43
        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
        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
    public function update($data = null, $whiteList = null): bool
70
    {
71
        //associate uploaded files
72
        if (isset($data['files'])) {
73
            if (!empty($data['files'])) {
74
                $this->uploadedFiles = $data['files'];
75
            } else {
76
                $this->deleteFiles();
77
            }
78
        }
79
80
        return parent::update($data, $whiteList);
81
    }
82
83
    /**
84
     * Inserts or updates a model instance. Returning true on success or false otherwise.
85
     *
86
     *<code>
87
     * // Creating a new robot
88
     * $robot = new Robots();
89
     *
90
     * $robot->type = "mechanical";
91
     * $robot->name = "Astro Boy";
92
     * $robot->year = 1952;
93
     *
94
     * $robot->save();
95
     *
96
     * // Updating a robot name
97
     * $robot = Robots::findFirst("id = 100");
98
     *
99
     * $robot->name = "Biomass";
100
     *
101
     * $robot->save();
102
     *</code>
103
     *
104
     * @param array data
105
     * @param array whiteList
106
     * @return boolean
107
     */
108
    public function save($data = null, $whiteList = null): bool
109
    {
110
        //associate uploaded files
111
        if (isset($data['files'])) {
112
            if (!empty($data['files'])) {
113
                $this->uploadedFiles = $data['files'];
114
            } else {
115
                $this->deleteFiles();
116
            }
117
        }
118
119
        return parent::save($data, $whiteList);
120
    }
121
122
    /**
123
     * Delete all the files from a module.
124
     *
125
     * @return bool
126
     */
127
    public function deleteFiles(): bool
128
    {
129
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
130
131
        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

131
        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

131
        if ($files = FileSystemEntities::getAllByEntityId($this->/** @scrutinizer ignore-call */ getId(), $systemModule)) {
Loading history...
132
            foreach ($files as $file) {
133
                $file->softDelete();
134
            }
135
        }
136
137
        return true;
138
    }
139
140
    /**
141
     * Given the ID delete the file from this entity.
142
     *
143
     * @param integer $id
144
     * @return bool
145
     */
146
    public function deleteFile(int $id)
147
    {
148
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
149
150
        $file = FileSystemEntities::findFirstOrFail([
151
            'contidions' => 'id = ?0 AND entity_id = ?1 AND system_modules_id = ?2 AND is_deleted = ?3',
152
            'bind' => [$id, $this->getId(), $systemModule->getId(), 0]
153
        ]);
154
155
        return $file->softDelete();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $file->softDelete() returns the type void which is incompatible with the documented return type boolean.
Loading history...
Bug introduced by
Are you sure the usage of $file->softDelete() targeting Baka\Database\Model::softDelete() 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...
156
    }
157
158
    /**
159
     * Given the array of files we will attch this files to the files.
160
     * [
161
     *  'file' => $file,
162
     *  'file_name' => 'dfadfa'
163
     * ];.
164
     *
165
     * @param array $files
166
     * @return void
167
     */
168
    public function attach(array $files): bool
169
    {
170
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
171
172
        foreach ($files as $file) {
173
            //im looking for the file inside an array
174
            if (!array_key_exists('file', $file)) {
175
                continue;
176
            }
177
178
            if (!$file['file'] instanceof FileSystem) {
179
                throw new RuntimeException('Cant attach a one Filesytem to this entity');
180
            }
181
182
            //check if we are updating the attachment
183
            if (array_key_exists('id', $file) && (int) $file['id']) {
184
                $fileSystemEntities = FileSystemEntities::getByIdWithSystemModule($file['id'], $systemModule);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $fileSystemEntities is correct as Canvas\Models\FileSystem...e['id'], $systemModule) 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...
185
            }
186
187
            //new attachment
188
            if (!is_object($fileSystemEntities)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $fileSystemEntities does not seem to be defined for all execution paths leading up to this point.
Loading history...
189
                $fileSystemEntities = new FileSystemEntities();
190
                $fileSystemEntities->system_modules_id = $systemModule->getId();
191
                $fileSystemEntities->companies_id = $file['file']->companies_id;
192
                $fileSystemEntities->entity_id = $this->getId();
193
                $fileSystemEntities->created_at = $file['file']->created_at;
194
            }
195
196
            $fileSystemEntities->filesystem_id = $file['file']->getId();
197
            $fileSystemEntities->field_name = $file['field_name'] ?? null;
198
            $fileSystemEntities->is_deleted = 0 ;
199
            $fileSystemEntities->saveOrFail();
200
201
            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...
202
                $file['file']->move($this->filesNewAttachedPath());
203
            }
204
        }
205
206
        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...
207
    }
208
209
    /**
210
     * Get all the files attach for the given module.
211
     *
212
     * @param string $fileType filter the files by their type
213
     * @return array
214
     */
215
    public function getAttachments(string $fileType = null) : ResultsetInterface
216
    {
217
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
218
        $companyId = $this->di->getUserData()->currentCompanyId();
219
220
        $bindParams = [
221
            $systemModule->getId(),
222
            $this->getId(),
223
            0,
224
            $companyId
225
        ];
226
227
        /**
228
         * We can also filter the attachements by its file type.
229
         */
230
        $fileTypeSql = !is_null($fileType) ? 'AND f.file_type = ?4' : null;
231
        if ($fileTypeSql) {
232
            $bindParams[] = $fileType;
233
        }
234
235
        return FileSystemEntities::find([
236
            'conditions' => 'system_modules_id = ?0 AND entity_id = ?1 AND is_deleted = ?2 and companies_id = ?3
237
                            AND filesystem_id IN (SELECT f.id from \Canvas\Models\FileSystem f WHERE
238
                                f.is_deleted = ?2 AND f.companies_id = ?3 ' . $fileTypeSql . '
239
                            )',
240
            'bind' => $bindParams
241
        ]);
242
    }
243
244
    /**
245
     * Overwrite the relationship of the filesystem to return the attachment structure
246
     * to the given user.
247
     *
248
     * @deprecated version 0.2
249
     * @return array
250
     */
251
    public function getFilesystem(): array
252
    {
253
        return $this->getFiles();
254
    }
255
256
    /**
257
     * Overwrite the relationship of the filesystem to return the attachment structure
258
     * to the given user.
259
     *
260
     * @return array
261
     */
262
    public function getFiles(string $fileType = null): array
263
    {
264
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
265
266
        $attachments = $this->getAttachments($fileType);
267
268
        $fileMapper = new FileMapper($this->getId(), $systemModule->getId());
269
270
        //add a mapper
271
        $this->di->getDtoConfig()->registerMapping(FileSystemEntities::class, Files::class)
272
            ->useCustomMapper($fileMapper);
273
274
        return $this->di->getMapper()->mapMultiple($attachments, Files::class);
275
    }
276
277
    /**
278
     * Get a file by its fieldname.
279
     *
280
     * @todo this will be a performance issue in the futur look for better ways to handle this
281
     * when a company has over 1k images
282
     *
283
     * @deprecated version 0.2
284
     * @param string $name
285
     * @return void
286
     */
287
    public function getAttachmentByName(string $fieldName)
288
    {
289
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
290
        $companyId = $this->di->getUserData()->currentCompanyId();
291
292
        return FileSystemEntities::findFirst([
293
            'conditions' => 'system_modules_id = ?0 AND entity_id = ?1 AND is_deleted = ?2 and field_name = ?3 and companies_id = ?4
294
                            AND filesystem_id IN (SELECT f.id from \Canvas\Models\FileSystem f WHERE
295
                                f.is_deleted = ?2 AND f.companies_id = ?4
296
                            )',
297
            'bind' => [$systemModule->getId(), $this->getId(), 0, $fieldName, $companyId]
298
        ]);
299
    }
300
301
    /**
302
     * Undocumented function.
303
     *
304
     * @param string $fieldName
305
     * @return string|null
306
     */
307
    public function getFileByName(string $fieldName): ?object
308
    {
309
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
310
311
        $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

311
        $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...
312
313
        if ($fileEntity) {
0 ignored issues
show
introduced by
$fileEntity is of type void, thus it always evaluated to false.
Loading history...
314
            $fileMapper = new FileMapper($this->getId(), $systemModule->getId());
315
316
            //add a mapper
317
            $this->di->getDtoConfig()->registerMapping(FileSystemEntities::class, Files::class)
318
                ->useCustomMapper($fileMapper);
319
320
            /**
321
             * @todo create a mapper for entity so we dont have to look for the relationship?
322
             */
323
            return $this->di->getMapper()->map($fileEntity, Files::class);
324
        }
325
326
        return null;
327
    }
328
329
    /**
330
     * Given this entity define a new path.
331
     *
332
     * @param string $path
333
     * @return string
334
     */
335
    protected function filesNewAttachedPath(): ?string
336
    {
337
        return null;
338
    }
339
}
340