Passed
Push — feature/permissions-management ( 3c8a9f...1cc208 )
by Harings
19:21 queued 10s
created

HandleRevisions   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 244
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 81
dl 0
loc 244
rs 10
c 2
b 0
f 0
wmc 27

12 Methods

Rating   Name   Duplication   Size   Complexity  
A hydrateMultiSelect() 0 14 4
A hydrateRepeater() 0 23 3
A beforeSaveHandleRevisions() 0 12 2
A hydrateBrowser() 0 3 1
A hydrateHandleRevisions() 0 15 4
A getCountByStatusSlugHandleRevisions() 0 7 2
A hydrateOrderedBelongsToMany() 0 19 4
A previewForRevision() 0 10 1
A hydrateObject() 0 9 1
A getCountForMine() 0 4 1
A preview() 0 5 1
A hydrateRelatedBrowsers() 0 30 3
1
<?php
2
3
namespace A17\Twill\Repositories\Behaviors;
4
5
use A17\Twill\Models\Behaviors\HasRelated;
6
use A17\Twill\Models\RelatedItem;
7
use Illuminate\Support\Arr;
8
use Illuminate\Support\Collection;
9
use Illuminate\Support\Facades\Auth;
10
11
trait HandleRevisions
12
{
13
    /**
14
     * @param \A17\Twill\Models\Model $object
15
     * @param array $fields
16
     * @return \A17\Twill\Models\Model
17
     */
18
    public function hydrateHandleRevisions($object, $fields)
19
    {
20
        foreach($this->getRepeaters() as $repeater) {
0 ignored issues
show
Bug introduced by
It seems like getRepeaters() 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

20
        foreach($this->/** @scrutinizer ignore-call */ getRepeaters() as $repeater) {
Loading history...
21
            $this->hydrateRepeater($object, $fields, $repeater['relation'], $repeater['model']);
22
        }
23
24
        foreach($this->getBrowsers() as $browser) {
0 ignored issues
show
Bug introduced by
It seems like getBrowsers() 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

24
        foreach($this->/** @scrutinizer ignore-call */ getBrowsers() as $browser) {
Loading history...
25
            $this->hydrateBrowser($object, $fields, $browser['relation'], $browser['positionAttribute'], $browser['model']);
26
        }
27
28
        if (classHasTrait(get_class($object), HasRelated::class)) {
29
            $this->hydrateRelatedBrowsers($object, $fields);
30
        }
31
32
        return $object;
33
    }
34
35
    /**
36
     * @param \A17\Twill\Models\Model $object
37
     * @param array $fields
38
     * @return array
39
     */
40
    public function beforeSaveHandleRevisions($object, $fields)
41
    {
42
        $lastRevisionPayload = json_decode($object->revisions->first()->payload ?? "{}", true);
0 ignored issues
show
Bug introduced by
The property revisions does not seem to exist on A17\Twill\Models\Model. 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...
43
44
        if ($fields != $lastRevisionPayload) {
45
            $object->revisions()->create([
46
                'payload' => json_encode($fields),
47
                'user_id' => Auth::guard('twill_users')->user()->id ?? null,
48
            ]);
49
        }
50
51
        return $fields;
52
    }
53
54
    /**
55
     * @param int $id
56
     * @param array $fields
57
     * @return \A17\Twill\Models\Model
58
     */
59
    public function preview($id, $fields)
60
    {
61
        $object = $this->model->findOrFail($id);
62
63
        return $this->hydrateObject($object, $fields);
64
    }
65
66
    /**
67
     * @param \A17\Twill\Models\Model $object
68
     * @param array $fields
69
     * @return \A17\Twill\Models\Model
70
     */
71
    protected function hydrateObject($object, $fields)
72
    {
73
        $fields = $this->prepareFieldsBeforeSave($object, $fields);
0 ignored issues
show
Bug introduced by
It seems like prepareFieldsBeforeSave() 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

73
        /** @scrutinizer ignore-call */ 
74
        $fields = $this->prepareFieldsBeforeSave($object, $fields);
Loading history...
74
75
        $object->fill(Arr::except($fields, $this->getReservedFields()));
0 ignored issues
show
Bug introduced by
It seems like getReservedFields() 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

75
        $object->fill(Arr::except($fields, $this->/** @scrutinizer ignore-call */ getReservedFields()));
Loading history...
76
77
        $object = $this->hydrate($object, $fields);
0 ignored issues
show
Bug introduced by
The method hydrate() does not exist on A17\Twill\Repositories\Behaviors\HandleRevisions. Did you maybe mean hydrateRepeater()? ( Ignorable by Annotation )

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

77
        /** @scrutinizer ignore-call */ 
78
        $object = $this->hydrate($object, $fields);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
78
79
        return $object;
80
    }
81
82
    /**
83
     * @param int $id
84
     * @param int $revisionId
85
     * @return \A17\Twill\Models\Model
86
     */
87
    public function previewForRevision($id, $revisionId)
88
    {
89
        $object = $this->model->findOrFail($id);
90
91
        $fields = json_decode($object->revisions->where('id', $revisionId)->first()->payload, true);
92
93
        $hydratedObject = $this->hydrateObject($this->model->newInstance(), $fields);
94
        $hydratedObject->id = $id;
95
96
        return $hydratedObject;
97
    }
98
99
    /**
100
     * @param \A17\Twill\Models\Model $object
101
     * @param array $fields
102
     * @param string $relationship
103
     * @param \A17\Twill\Models\Model|null $model
104
     * @param string|null $customHydratedRelationship
105
     * @return void
106
     */
107
    public function hydrateMultiSelect($object, $fields, $relationship, $model = null, $customHydratedRelationship = null)
108
    {
109
        $fieldsHasElements = isset($fields[$relationship]) && !empty($fields[$relationship]);
110
        $relatedElements = $fieldsHasElements ? $fields[$relationship] : [];
111
112
        $relationRepository = $this->getModelRepository($relationship, $model);
0 ignored issues
show
Bug introduced by
It seems like getModelRepository() 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

112
        /** @scrutinizer ignore-call */ 
113
        $relationRepository = $this->getModelRepository($relationship, $model);
Loading history...
113
        $relatedElementsCollection = Collection::make();
114
115
        foreach ($relatedElements as $relatedElement) {
116
            $newRelatedElement = $relationRepository->getById($relatedElement);
117
            $relatedElementsCollection->push($newRelatedElement);
118
        }
119
120
        $object->setRelation($customHydratedRelationship ?? $relationship, $relatedElementsCollection);
121
    }
122
123
    /**
124
     * @param \A17\Twill\Models\Model $object
125
     * @param array $fields
126
     * @param string $relationship
127
     * @param string $positionAttribute
128
     * @param \A17\Twill\Models\Model|null $model
129
     * @return null
130
     */
131
    public function hydrateBrowser($object, $fields, $relationship, $positionAttribute = 'position', $model = null)
132
    {
133
        return $this->hydrateOrderedBelongsToMany($object, $fields, $relationship, $positionAttribute, $model);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->hydrateOrderedBel...itionAttribute, $model) targeting A17\Twill\Repositories\B...eOrderedBelongsToMany() 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...
134
    }
135
136
    /**
137
     * @param \A17\Twill\Models\Model $object
138
     * @param array $fields
139
     * @param string $relationship
140
     * @param string $positionAttribute
141
     * @param \A17\Twill\Models\Model|null $model
142
     * @return void
143
     */
144
    public function hydrateOrderedBelongsToMany($object, $fields, $relationship, $positionAttribute = 'position', $model = null)
145
    {
146
        $fieldsHasElements = isset($fields['browsers'][$relationship]) && !empty($fields['browsers'][$relationship]);
147
        $relatedElements = $fieldsHasElements ? $fields['browsers'][$relationship] : [];
148
149
        $relationRepository = $this->getModelRepository($relationship, $model);
150
        $relatedElementsCollection = Collection::make();
151
        $position = 1;
152
153
        $tableName = $relationRepository->model->getTable();
154
155
        foreach ($relatedElements as $relatedElement) {
156
            $newRelatedElement = $relationRepository->getById($relatedElement['id']);
157
            $pivot = $newRelatedElement->newPivot($object, [$positionAttribute => $position++], $tableName, true);
158
            $newRelatedElement->setRelation('pivot', $pivot);
159
            $relatedElementsCollection->push($newRelatedElement);
160
        }
161
162
        $object->setRelation($relationship, $relatedElementsCollection);
163
    }
164
165
    /**
166
     * @param \A17\Twill\Models\Model $object
167
     * @param array $fields
168
     * @return void
169
     */
170
    public function hydrateRelatedBrowsers($object, $fields)
171
    {
172
        $relatedBrowsers = $this->getRelatedBrowsers();
0 ignored issues
show
Bug introduced by
It seems like getRelatedBrowsers() 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

172
        /** @scrutinizer ignore-call */ 
173
        $relatedBrowsers = $this->getRelatedBrowsers();
Loading history...
173
174
        $initialRelatedItems = $object->relatedItems()
175
            ->whereNotIn('browser_name', $relatedBrowsers->pluck('browserName'))
176
            ->get();
177
178
        $relatedBrowserItems = collect();
179
180
        foreach ($relatedBrowsers as $browser) {
181
            $browserField = $fields['browsers'][$browser['browserName']] ?? [];
182
183
            foreach ($browserField as $values) {
184
                $position = 1;
185
186
                $relatedBrowserItems->push(RelatedItem::make([
187
                    'subject_id' => $object->getKey(),
188
                    'subject_type' => $object->getMorphClass(),
189
                    'related_id' => $values['id'],
190
                    'related_type' => $values['endpointType'],
191
                    'browser_name' => $browser['browserName'],
192
                    'position' => $position++,
193
                ]));
194
            }
195
        }
196
197
        $allRelatedItems = $relatedBrowserItems->concat($initialRelatedItems);
198
199
        $object->setRelation('relatedItems', $allRelatedItems);
200
    }
201
202
    /**
203
     * @param \A17\Twill\Models\Model $object
204
     * @param array $fields
205
     * @param string $relationship
206
     * @param \A17\Twill\Models\Model $model
207
     * @param string|null $repeaterName
208
     * @return void
209
     */
210
    public function hydrateRepeater($object, $fields, $relationship, $model, $repeaterName = null)
211
    {
212
        if (!$repeaterName) {
213
            $repeaterName = $relationship;
214
        }
215
216
        $relationFields = $fields['repeaters'][$repeaterName] ?? [];
217
218
        $relationRepository = getModelRepository($relationship, $model);
219
220
        $repeaterCollection = Collection::make();
221
222
        foreach ($relationFields as $index => $relationField) {
223
            $relationField['position'] = $index + 1;
224
            $relationField[$this->model->getForeignKey()] = $object->id;
225
            unset($relationField['id']);
226
227
            $newRepeater = $relationRepository->createForPreview($relationField);
0 ignored issues
show
Bug introduced by
The method createForPreview() does not exist on Illuminate\Contracts\Foundation\Application. ( Ignorable by Annotation )

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

227
            /** @scrutinizer ignore-call */ 
228
            $newRepeater = $relationRepository->createForPreview($relationField);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
228
229
            $repeaterCollection->push($newRepeater);
230
        }
231
232
        $object->setRelation($relationship, $repeaterCollection);
233
    }
234
235
    /**
236
     * @return int
237
     */
238
    public function getCountForMine()
239
    {
240
        $query = $this->model->newQuery();
241
        return $this->filter($query, $this->countScope)->mine()->count();
0 ignored issues
show
Bug introduced by
It seems like filter() 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

241
        return $this->/** @scrutinizer ignore-call */ filter($query, $this->countScope)->mine()->count();
Loading history...
242
    }
243
244
    /**
245
     * @param string $slug
246
     * @return int|bool
247
     */
248
    public function getCountByStatusSlugHandleRevisions($slug)
249
    {
250
        if ($slug === 'mine') {
251
            return $this->getCountForMine();
252
        }
253
254
        return false;
255
    }
256
}
257