Passed
Push — master ( 7c331b...3c78de )
by Jonathan
18:06
created

UccelloModule::initializeUccelloModule()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Uccello\Core\Support\Traits;
4
5
use Uccello\Core\Models\Entity;
6
use Uccello\Core\Models\Module;
7
use Uccello\Core\Models\Filter;
8
use Illuminate\Support\Facades\Cache;
0 ignored issues
show
Bug introduced by
The type Illuminate\Support\Facades\Cache 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...
9
use Uccello\Core\Support\Scopes;
10
use Illuminate\Support\Facades\Auth;
0 ignored issues
show
Bug introduced by
The type Illuminate\Support\Facades\Auth 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 Illuminate\Support\Facades\Schema;
0 ignored issues
show
Bug introduced by
The type Illuminate\Support\Facades\Schema 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...
12
use Illuminate\Support\Str;
0 ignored issues
show
Bug introduced by
The type Illuminate\Support\Str 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...
13
use Uccello\Core\Models\Domain;
14
15
trait UccelloModule
16
{
17
    use RelatedlistTrait;
18
19
    /**
20
     * The "booting" method of the trait.
21
     *
22
     * @return void
23
     */
24
    protected static function bootUccelloModule()
25
    {
26
        if (static::isFilteredByUser()) {
27
            static::addGlobalScope(new Scopes\AssignedUser);
28
        }
29
30
        // Create uuid after save
31
        static::created(function ($model) {
32
            $module = Module::where('model_class', get_class($model))->first();
33
            if ($module) {
34
                Entity::create([
35
                    'id' => (string) Str::uuid(),
36
                    'module_id' => $module->id,
37
                    'record_id' => $model->getKey(),
38
                    'creator_id' => auth()->id(),
0 ignored issues
show
Bug introduced by
The function auth was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

38
                    'creator_id' => /** @scrutinizer ignore-call */ auth()->id(),
Loading history...
39
                ]);
40
            }
41
        });
42
43
        // Delete uuid after forced delete
44
        static::deleted(function ($model) {
45
            if (!empty($model->uuid) && (!method_exists($model, 'isForceDeleting') || $model->isForceDeleting() === true)) {
46
                $entity = Entity::find($model->uuid);
47
                if ($entity) {
48
                    $entity->delete();
49
                }
50
            }
51
        });
52
    }
53
54
    public function initializeUccelloModule()
55
    {
56
        $this->appends = array_merge($this->appends, ['recordLabel','uuid']);
0 ignored issues
show
Bug Best Practice introduced by
The property appends does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
57
    }
58
59
    protected static function isFilteredByUser()
60
    {
61
        $isFilteredByUser = false;
62
63
        $user = Auth::user();
64
65
        if ($user && !$user->is_admin) {
66
            $module = static::getModuleFromClass(static::class);
67
68
            if ($module && $module->data && property_exists($module->data, 'private') && $module->data->private) {
69
                $isFilteredByUser = true;
70
            }
71
        }
72
73
        return $isFilteredByUser;
74
    }
75
76
    public function getTableAttribute()
77
    {
78
        return $this->table;
79
    }
80
81
    public function getModuleAttribute()
82
    {
83
        return static::getModuleFromClass(get_class($this));
84
    }
85
86
    protected static function getModuleFromClass($className)
87
    {
88
        $modules = Cache::rememberForever('modules_by_model_class', function () {
89
            $modulesGroupedByModelClass = collect();
0 ignored issues
show
Bug introduced by
The function collect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

89
            $modulesGroupedByModelClass = /** @scrutinizer ignore-call */ collect();
Loading history...
90
            Module::all()->map(function ($item) use ($modulesGroupedByModelClass) {
91
                $modulesGroupedByModelClass[$item->model_class] = $item;
92
                return $modulesGroupedByModelClass;
93
            });
94
            return $modulesGroupedByModelClass;
95
        });
96
        return $modules[(string) $className] ?? null;
97
    }
98
99
    public function getUuidAttribute()
100
    {
101
        $uuid = null;
102
103
        $module = $this->module;
104
105
        if ($module) {
106
            $entity = Entity::where('module_id', $module->getKey())
107
                ->where('record_id', $this->getKey())
0 ignored issues
show
Bug introduced by
It seems like getKey() 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

107
                ->where('record_id', $this->/** @scrutinizer ignore-call */ getKey())
Loading history...
108
                ->first();
109
110
            if ($entity) {
111
                $uuid = $entity->getKey();
112
            }
113
        }
114
115
        return $uuid;
116
    }
117
118
    /**
119
     * Returns Assigned User
120
     *
121
     * @return string|null
122
     */
123
    public function getAssignedUserAttribute(): ?string
124
    {
125
        return $this->assigned_user_id;
126
    }
127
128
    /**
129
     * Returns user who created the entity, if defined.
130
     *
131
     * @return \Uccello\Core\Models\User|null
132
     */
133
    public function getCreatorAttribute()
134
    {
135
        $creator = null;
136
137
        $module = $this->module;
138
139
        if ($module) {
140
            $entity = Entity::where('module_id', $module->getKey())
141
                ->where('record_id', $this->getKey())
142
                ->first();
143
144
            if ($entity) {
145
                $creator = $entity->creator;
146
            }
147
        }
148
149
        return $creator;
150
    }
151
152
    public function scopeInDomain($query, ?Domain $domain, $withDescendants = false)
153
    {
154
        if (!empty($domain) && Schema::hasColumn($this->table, 'domain_id')) {
155
            // Activate descendant view if the user is allowed
156
            if (Auth::user() && Auth::user()->canSeeDescendantsRecords($domain) && $withDescendants) {
157
                $domainsIds = $domain->findDescendants()->pluck('id');
158
                $query = $query->whereIn('domain_id', $domainsIds);
159
            } else {
160
                $query = $query->where('domain_id', $domain->id);
161
            }
162
        }
163
164
        return $query;
165
    }
166
167
    /**
168
     * Add filter conditions to a query.
169
     * @param QueryBuilder $query
0 ignored issues
show
Bug introduced by
The type Uccello\Core\Support\Traits\QueryBuilder 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...
170
     * @param Filter|int|array $filter
171
     * @return QueryBuilder|null
172
     */
173
    public function scopeFilterBy($query, $filter)
174
    {
175
        $filterModel = null;
176
177
        if (!empty($filter)) {
178
            // $filter: int id
179
            if (is_numeric($filter)) {
180
                // TODO: Check permissions ?? (domain, user)
181
                $filterModel = Filter::where('id', $filter)
182
                                        ->where('module_id', $this->module->getKey())
183
                                        ->first();
184
            }
185
            // $filter: array data
186
            elseif (is_array($filter)) {
187
                $filterModel = Filter::newFromData($filter);
188
            }
189
            // $filter: Filter model
190
            elseif (substr(strrchr(get_class($filter), "\\"), 1) == 'Filter') {
191
                $filterModel = $filter;
192
            }
193
194
            if ($filterModel) {
195
                // Conditions
196
                if (!empty($filterModel->conditions)) {
197
                    // Search
198
                    if (!empty($filterModel->conditions->search)) {
199
                        foreach ($filterModel->conditions->search as $fieldName => $searchValue) {
200
                            // Get field by name and search by field column
201
                            $field = $this->module->getField($fieldName);
202
                            if (isset($searchValue) && !is_null($field)) {
203
                                $uitype = uitype($field->uitype_id);
204
                                $query = $uitype->addConditionToSearchQuery($query, $field, $searchValue);
205
                            }
206
                        }
207
                    }
208
                }
209
210
                // Order results
211
                if (!empty($filterModel->order)) {
212
                    foreach ($filterModel->order as $fieldName => $value) {
213
                        // Get field by name and search by field column
214
                        $field = $this->module->getField($fieldName);
215
                        if (!is_null($field)) {
216
                            $query = $query->orderBy($field->column, $value);
217
                        }
218
                    }
219
                }
220
            }
221
        }
222
223
        return $query;
224
    }
225
}
226