Passed
Push — 1.2 ( 392f29...968e7d )
by Quentin
08:39 queued 03:08
created

HandleRevisions::hydrateHandleRevisions()   C

Complexity

Conditions 14
Paths 4

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 19
nc 4
nop 2
dl 0
loc 29
rs 6.2666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace A17\Twill\Repositories\Behaviors;
4
5
use Illuminate\Support\Arr;
6
use Illuminate\Support\Facades\Auth;
7
use Illuminate\Support\Collection;
8
9
trait HandleRevisions
10
{
11
    public function hydrateHandleRevisions($object, $fields)
12
    {
13
        if (property_exists($this, 'browsers')) {
14
            foreach ($this->browsers as $module) {
15
                if (is_string($module)) {
16
                    $this->hydrateBrowser($object, $fields, $module);
17
                } elseif (is_array($module)) {
18
                    $relation = !empty($module['relation']) ? $module['relation'] : key($module);
19
                    $positionAttribute = !empty($module['positionAttribute']) ? $module['positionAttribute'] : 'position';
20
                    $model = isset($module['model']) ? $module['model'] : null;
21
                    $this->hydrateBrowser($object, $fields, $relation, $positionAttribute, $model);
22
                }
23
            }
24
        }
25
26
        if (property_exists($this, 'repeaters')) {
27
            foreach ($this->repeaters as $module) {
28
                if (is_string($module)) {
29
                    $model = Str::studly(Str::singular($module));
0 ignored issues
show
Bug introduced by
The type A17\Twill\Repositories\Behaviors\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...
30
                    $this->hydrateRepeater($object, $fields, $module, $model);
31
                } elseif (is_array($module)) {
32
                    $relation = !empty($module['relation']) ? $module['relation'] : key($module);
33
                    $model = isset($module['model']) ? $module['model'] : Str::studly(Str::singular(key($module)));
34
                    $this->hydrateRepeater($object, $fields, $relation, $model);
35
                }
36
            }
37
        }
38
39
        return $object;
40
    }
41
42
    public function beforeSaveHandleRevisions($object, $fields)
43
    {
44
        $lastRevisionPayload = json_decode($object->revisions->first()->payload ?? "{}", true);
45
46
        if ($fields != $lastRevisionPayload) {
47
            $object->revisions()->create([
48
                'payload' => json_encode($fields),
49
                'user_id' => Auth::guard('twill_users')->user()->id ?? null,
50
            ]);
51
        }
52
53
        return $fields;
54
    }
55
56
    public function preview($id, $fields)
57
    {
58
        $object = $this->model->findOrFail($id);
59
60
        return $this->hydrateObject($object, $fields);
61
    }
62
63
    protected function hydrateObject($object, $fields)
64
    {
65
        $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

65
        /** @scrutinizer ignore-call */ 
66
        $fields = $this->prepareFieldsBeforeSave($object, $fields);
Loading history...
66
67
        $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

67
        $object->fill(Arr::except($fields, $this->/** @scrutinizer ignore-call */ getReservedFields()));
Loading history...
68
69
        $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 hydrateOrderedBelongsTomany()? ( Ignorable by Annotation )

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

69
        /** @scrutinizer ignore-call */ 
70
        $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...
70
71
        return $object;
72
    }
73
74
    public function previewForRevision($id, $revisionId)
75
    {
76
        $object = $this->model->findOrFail($id);
77
78
        $fields = json_decode($object->revisions->where('id', $revisionId)->first()->payload, true);
79
80
        $hydratedObject = $this->hydrateObject($this->model->newInstance(), $fields);
81
        $hydratedObject->id = $id;
82
83
        return $hydratedObject;
84
    }
85
86
    public function hydrateMultiSelect($object, $fields, $relationship, $model = null, $customHydratedRelationship = null)
87
    {
88
        $fieldsHasElements = isset($fields[$relationship]) && !empty($fields[$relationship]);
89
        $relatedElements = $fieldsHasElements ? $fields[$relationship] : [];
90
91
        $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

91
        /** @scrutinizer ignore-call */ 
92
        $relationRepository = $this->getModelRepository($relationship, $model);
Loading history...
92
        $relatedElementsCollection = Collection::make();
93
94
        foreach ($relatedElements as $relatedElement) {
95
            $newRelatedElement = $relationRepository->getById($relatedElement);
96
            $relatedElementsCollection->push($newRelatedElement);
97
        }
98
99
        $object->setRelation($customHydratedRelationship ?? $relationship, $relatedElementsCollection);
100
    }
101
102
    public function hydrateBrowser($object, $fields, $relationship, $positionAttribute = 'position', $model = null)
103
    {
104
        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...
105
    }
106
107
    public function hydrateOrderedBelongsTomany($object, $fields, $relationship, $positionAttribute = 'position', $model = null)
108
    {
109
        $fieldsHasElements = isset($fields['browsers'][$relationship]) && !empty($fields['browsers'][$relationship]);
110
        $relatedElements = $fieldsHasElements ? $fields['browsers'][$relationship] : [];
111
112
        $relationRepository = $this->getModelRepository($relationship, $model);
113
        $relatedElementsCollection = Collection::make();
114
        $position = 1;
115
116
        foreach ($relatedElements as $relatedElement) {
117
            $newRelatedElement = $relationRepository->getById($relatedElement['id']);
118
            $pivot = $newRelatedElement->newPivot($object, [$positionAttribute => $position++], $object->$relationship()->getTable(), true);
119
            $newRelatedElement->setRelation('pivot', $pivot);
120
            $relatedElementsCollection->push($newRelatedElement);
121
        }
122
123
        $object->setRelation($relationship, $relatedElementsCollection);
124
    }
125
126
    public function hydrateRepeater($object, $fields, $relationship, $model)
127
    {
128
        $relationFields = $fields['repeaters'][$relationship] ?? [];
129
130
        $relationRepository = $this->getModelRepository($relationship, $model);
131
132
        $repeaterCollection = Collection::make();
133
134
        foreach ($relationFields as $index => $relationField) {
135
            $relationField['position'] = $index + 1;
136
            $relationField[$this->model->getForeignKey()] = $object->id;
137
            unset($relationField['id']);
138
139
            $newRepeater = $relationRepository->createForPreview($relationField);
140
141
            $repeaterCollection->push($newRepeater);
142
        }
143
144
        $object->setRelation($relationship, $repeaterCollection);
145
    }
146
147
    public function getCountForMine()
148
    {
149
        $query = $this->model->newQuery();
150
        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

150
        return $this->/** @scrutinizer ignore-call */ filter($query, $this->countScope)->mine()->count();
Loading history...
151
    }
152
153
    public function getCountByStatusSlugHandleRevisions($slug)
154
    {
155
        if ($slug === 'mine') {
156
            return $this->getCountForMine();
157
        }
158
159
        return false;
160
    }
161
}
162