Passed
Push — master ( 4ae7b3...54d2c2 )
by Jonathan
09:15
created

UccelloModule::getModuleFromClass()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 7
c 2
b 0
f 0
dl 0
loc 11
rs 10
cc 1
nc 1
nop 1
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;
9
use Uccello\Core\Support\Scopes;
10
use Illuminate\Support\Facades\Auth;
11
use Illuminate\Support\Facades\Schema;
12
use Illuminate\Support\Str;
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
                ]);
39
            }
40
        });
41
42
        // Delete uuid after forced delete
43
        static::deleted(function ($model) {
44
            if (!empty($model->uuid) && (!method_exists($model, 'isForceDeleting') || $model->isForceDeleting() === true)) {
45
                $entity = Entity::find($model->uuid);
46
                if ($entity) {
47
                    $entity->delete();
48
                }
49
            }
50
        });
51
    }
52
53
    public function initializeUccelloModule()
54
    {
55
        $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...
56
    }
57
58
    protected static function isFilteredByUser()
59
    {
60
        $isFilteredByUser = false;
61
62
        $user = Auth::user();
63
64
        if ($user && !$user->is_admin) {
0 ignored issues
show
Bug introduced by
Accessing is_admin on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
65
            $module = static::getModuleFromClass(static::class);
66
67
            if ($module && $module->data && property_exists($module->data, 'private') && $module->data->private) {
68
                $isFilteredByUser = true;
69
            }
70
        }
71
72
        return $isFilteredByUser;
73
    }
74
75
    public function getTableAttribute()
76
    {
77
        return $this->table;
78
    }
79
80
    public function getModuleAttribute()
81
    {
82
        return static::getModuleFromClass(get_class($this));
83
    }
84
85
    protected static function getModuleFromClass($className)
86
    {
87
        $modules = Cache::rememberForever('modules_by_model_class', function () {
88
            $modulesGroupedByModelClass = collect();
89
            Module::all()->map(function ($item) use ($modulesGroupedByModelClass) {
90
                $modulesGroupedByModelClass[$item->model_class] = $item;
91
                return $modulesGroupedByModelClass;
92
            });
93
            return $modulesGroupedByModelClass;
94
        });
95
        return $modules[(string) $className] ?? null;
96
    }
97
98
    public function getUuidAttribute()
99
    {
100
        $uuid = null;
101
102
        $entity = Entity::where('module_id', $this->module->getKey())
103
                        ->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

103
                        ->where('record_id', $this->/** @scrutinizer ignore-call */ getKey())
Loading history...
104
                        ->first();
105
106
        if ($entity) {
107
            $uuid = $entity->getKey();
108
        }
109
110
        return $uuid;
111
    }
112
113
    /**
114
     * Returns Assigned User
115
     *
116
     * @return string|null
117
     */
118
    public function getAssignedUserAttribute(): ?string
119
    {
120
        return $this->assigned_user_id;
121
    }
122
123
    public function scopeInDomain($query, ?Domain $domain, $withDescendants = false)
124
    {
125
        if (!empty($domain) && Schema::hasColumn($this->table, 'domain_id')) {
126
            // Activate descendant view if the user is allowed
127
            if (Auth::user()->canSeeDescendantsRecords($domain) && $withDescendants) {
0 ignored issues
show
Bug introduced by
The method canSeeDescendantsRecords() does not exist on Illuminate\Contracts\Auth\Authenticatable. It seems like you code against a sub-type of Illuminate\Contracts\Auth\Authenticatable such as Illuminate\Foundation\Auth\User. ( Ignorable by Annotation )

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

127
            if (Auth::user()->/** @scrutinizer ignore-call */ canSeeDescendantsRecords($domain) && $withDescendants) {
Loading history...
128
                $domainsIds = $domain->findDescendants()->pluck('id');
129
                $query = $query->whereIn('domain_id', $domainsIds);
130
            } else {
131
                $query = $query->where('domain_id', $domain->id);
132
            }
133
        }
134
135
        return $query;
136
    }
137
138
    /**
139
     * Returns Assigned User
140
     * @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...
141
     * @param Field|int|array $filter
0 ignored issues
show
Bug introduced by
The type Uccello\Core\Support\Traits\Field 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...
142
     * @return QueryBuilder|null
143
     */
144
    public function scopeFilterBy($query, $filter)
145
    {
146
        $filterModel = null;
147
148
        if (!empty($filter)) {
149
            // $filter: int id
150
            if (is_numeric($filter)) {
151
                // TODO: Check permissions ?? (domain, user)
152
                $filterModel = Filter::where('id', $filter)
153
                                        ->where('module_id', $this->module->getKey())
154
                                        ->first();
155
            }
156
            // $filter: array data
157
            elseif (is_array($filter)) {
158
                $filterModel = Filter::newFromData($filter);
159
            }
160
            // $filter: Filter model
161
            elseif (substr(strrchr(get_class($filter), "\\"), 1) == 'Filter') {
162
                $filterModel = $filter;
163
            }
164
165
            if ($filterModel) {
166
                // Conditions
167
                if (!empty($filterModel->conditions)) {
168
                    // Search
169
                    if (!empty($filterModel->conditions->search)) {
0 ignored issues
show
Bug introduced by
The property conditions does not seem to exist on Uccello\Core\Models\Filter. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
170
                        foreach ($filterModel->conditions->search as $fieldName => $searchValue) {
171
                            // Get field by name and search by field column
172
                            $field = $this->module->getField($fieldName);
173
                            if (isset($searchValue) && !is_null($field)) {
174
                                $uitype = uitype($field->uitype_id);
175
                                $query = $uitype->addConditionToSearchQuery($query, $field, $searchValue);
176
                            }
177
                        }
178
                    }
179
                }
180
181
                // Order results
182
                if (!empty($filterModel->order)) {
183
                    foreach ($filterModel->order as $fieldName => $value) {
0 ignored issues
show
Bug introduced by
The property order does not seem to exist on Uccello\Core\Models\Filter. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
184
                        // Get field by name and search by field column
185
                        $field = $this->module->getField($fieldName);
186
                        if (!is_null($field)) {
187
                            $query = $query->orderBy($field->column, $value);
188
                        }
189
                    }
190
                }
191
            }
192
        }
193
194
        return $query;
195
    }
196
}
197