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

FileSystemModelTrait::associateFileSystem()   A

Complexity

Conditions 6
Paths 2

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

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

121
        if ($files = FileSystem::getAllByEntityId($this->/** @scrutinizer ignore-call */ getId(), $systemModule)) {
Loading history...
122
            foreach ($files as $file) {
123
                $file->softDelete();
124
            }
125
        }
126
127
        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...
128
    }
129
130
    /**
131
     * Given the array of files we will attch this files to the files.
132
     * [
133
     *  'file' => $file,
134
     *  'file_name' => 'dfadfa'
135
     * ];.
136
     *
137
     * @param array $files
138
     * @return void
139
     */
140
    public function attach(array $files): bool
141
    {
142
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
143
        
144
        foreach ($files as $file) {
145
            //im looking for the file inside an array
146
            if (!array_key_exists('file', $file)) {
147
                continue;
148
            }
149
150
            if (!$file['file'] instanceof FileSystem) {
151
                throw new RuntimeException('Cant attach a one Filesytem to this entity');
152
            }
153
154
            //attach to the entity
155
            $fileSystemEntities = new FileSystemEntities();
156
            $fileSystemEntities->filesystem_id = $file['file']->getId();
157
            $fileSystemEntities->entity_id = $this->getId();
158
            $fileSystemEntities->system_modules_id = $systemModule->getId();
159
            $fileSystemEntities->field_name = $file['field_name'] ?? null;
160
            $fileSystemEntities->created_at = $file['file']->created_at;
161
            $fileSystemEntities->is_deleted = 0 ;
162
            $fileSystemEntities->saveOrFail();
163
        }
164
165
        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...
166
    }
167
168
    /**
169
     * Get all the files attach for the given module.
170
     *
171
     * @param string $fileType filter the files by their type
172
     * @return array
173
     */
174
    public function getAttachments(string $fileType = null) : array
175
    {
176
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
177
        $bindParams = [
178
            0,
179
            Di::getDefault()->getUserData()->currentCompanyId(),
180
            $systemModule->getId(),
181
            $this->getId()
182
        ];
183
184
        /**
185
         * We can also filter the attachements by its file type.
186
         */
187
        $fileTypeSql = !is_null($fileType) ? 'AND file_type = ?3' : null;
188
        if ($fileTypeSql) {
189
            $bindParams[] = $fileType;
190
        }
191
192
        $attachments = FileSystem::find([
193
            'conditions' => '
194
                is_deleted = ?0 AND companies_id = ?1 AND id in 
195
                    (SELECT 
196
                        filesystem_id from \Canvas\Models\FileSystemEntities e
197
                        WHERE e.system_modules_id = ?2 AND e.entity_id = ?3
198
                    )' . $fileTypeSql,
199
            'bind' => $bindParams
200
        ]);
201
202
        $fileMapper = new FileMapper();
203
        $fileMapper->systemModuleId = $systemModule->getId();
204
        $fileMapper->entityId = $this->getId();
205
206
        //add a mapper
207
        $this->di->getDtoConfig()->registerMapping(FileSystem::class, Files::class)
208
            ->useCustomMapper($fileMapper);
209
210
        return $this->di->getMapper()->mapMultiple($attachments, Files::class);
211
    }
212
213
    /**
214
     * Overwrite the relationship of the filesystem to return the attachment structure
215
     * to the given user.
216
     *
217
     * @return array
218
     */
219
    public function getFilesystem(): array
220
    {
221
        return $this->getAttachments();
222
    }
223
}
224