Test Failed
Push — master ( f4bd20...cb3e61 )
by Maximo
11:53 queued 06:36
created

FileSystemModelTrait::filesNewAttachedPath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
c 1
b 0
f 1
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
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
                /**
45
                 * @todo remove when all the frontend standardize our request
46
                 */
47
                if (!isset($file['id']) && (int) $file > 0) {
48
                    $file = ['id' => $file];
49
                }
50
51
                if (!isset($file['id'])) {
52
                    continue;
53
                }
54
55
                if ($fileSystem = FileSystem::getById($file['id'])) {
56
                    $this->attach([[
57
                        'file' => $fileSystem,
58
                        'field_name' => $file['field_name'] ?? ''
59
                    ]]);
60
                }
61
            }
62
        }
63
64
        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...
65
    }
66
67
    /**
68
     * Over write, because of the phalcon events.
69
     *
70
     * @param array data
71
     * @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...
72
     * @return boolean
73
     */
74
    public function update($data = null, $whiteList = null): bool
75
    {
76
        //associate uploaded files
77
        if (isset($data['files'])) {
78
            $this->uploadedFiles = $data['files'];
79
        } elseif (isset($data['filesystem_files'])) {
80
            $this->uploadedFiles = $data['filesystem_files'];
81
        }
82
83
        return parent::update($data, $whiteList);
84
    }
85
86
    /**
87
     * Inserts or updates a model instance. Returning true on success or false otherwise.
88
     *
89
     *<code>
90
     * // Creating a new robot
91
     * $robot = new Robots();
92
     *
93
     * $robot->type = "mechanical";
94
     * $robot->name = "Astro Boy";
95
     * $robot->year = 1952;
96
     *
97
     * $robot->save();
98
     *
99
     * // Updating a robot name
100
     * $robot = Robots::findFirst("id = 100");
101
     *
102
     * $robot->name = "Biomass";
103
     *
104
     * $robot->save();
105
     *</code>
106
     *
107
     * @param array data
108
     * @param array whiteList
109
     * @return boolean
110
     */
111
    public function save($data = null, $whiteList = null): bool
112
    {
113
        //associate uploaded files
114
        if (isset($data['files'])) {
115
            $this->uploadedFiles = $data['files'];
116
        } elseif (isset($data['filesystem_files'])) {
117
            $this->uploadedFiles = $data['filesystem_files'];
118
        }
119
120
        return parent::save($data, $whiteList);
121
    }
122
123
    /**
124
     * Delete all the files from a module.
125
     *
126
     * @return bool
127
     */
128
    public function deleteFiles(): bool
129
    {
130
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
131
132
        if ($files = FileSystem::getAllByEntityId($this->getId(), $systemModule)) {
0 ignored issues
show
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

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