Passed
Pull Request — 1.2 (#558)
by
unknown
09:10
created

HandleBrowsers::getBrowsers()   B

Complexity

Conditions 7
Paths 1

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 30.0568

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 10
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 13
ccs 2
cts 9
cp 0.2222
crap 30.0568
rs 8.8333
1
<?php
2
3
namespace A17\Twill\Repositories\Behaviors;
4
5
use Illuminate\Support\Str;
6
7
trait HandleBrowsers
8
{
9
    /**
10
     * All browsers used in the model, as an array of browser names: 
11
     * [
12
     *  'books',
13
     *  'publications'
14
     * ].
15
     * 
16
     * When only the browser name is given here, its rest information will be inferred from the name.
17
     * Each browser's detail can also be override with an array
18
     * [
19
     *  'books',
20
     *  'publication' => [
21
     *      'routePrefix' => 'collections',
22
     *      'titleKey' => 'name'
23
     *  ]
24
     * ]
25
     *
26
     * @var string|array(array)|array(mix(string|array))
27
     */
28
    protected $browsers = [];
29
30
    /**
31
     * @param \A17\Twill\Models\Model $object
32
     * @param array $fields
33
     * @return void
34
     */
35 27
    public function afterSaveHandleBrowsers($object, $fields)
36
    {
37 27
        foreach ($this->getBrowsers() as $browser) {
38
            $this->updateBrowser($object, $fields, $browser['relation'], $browser['positionAttribute'], $browser['browserName']);
39
        }
40 27
    }
41
42
    /**
43
     * @param \A17\Twill\Models\Model $object
44
     * @param array $fields
45
     * @return array
46
     */
47 5
    public function getFormFieldsHandleBrowsers($object, $fields)
48
    {
49 5
        foreach ($this->getBrowsers() as $browser) {
50
            $fields['browsers'][$browser['browserName']] = $this->getFormFieldsForBrowser($object, $browser['relation'], $browser['routePrefix'], $browser['titleKey'], $browser['moduleName']);
51
        }
52
53 5
        return $fields;
54
    }
55
56
    /**
57
     * @param \A17\Twill\Models\Model $object
58
     * @param array $fields
59
     * @param string $relationship
60
     * @param string $positionAttribute
61
     * @return void
62
     */
63
    public function updateBrowser($object, $fields, $relationship, $positionAttribute = 'position', $browserName = null)
64
    {
65
        $browserName = $browserName ?? $relationship;
66
        $fieldsHasElements = isset($fields['browsers'][$browserName]) && !empty($fields['browsers'][$browserName]);
67
        $relatedElements = $fieldsHasElements ? $fields['browsers'][$browserName] : [];
68
        $relatedElementsWithPosition = [];
69
        $position = 1;
70
        foreach ($relatedElements as $relatedElement) {
71
            $relatedElementsWithPosition[$relatedElement['id']] = [$positionAttribute => $position++];
72
        }
73
74
        $object->$relationship()->sync($relatedElementsWithPosition);
75
    }
76
77
    /**
78
     * @param \A17\Twill\Models\Model $object
79
     * @param array $fields
80
     * @param string $relationship
81
     * @param string $positionAttribute
82
     * @return void
83
     */
84
    public function updateOrderedBelongsTomany($object, $fields, $relationship, $positionAttribute = 'position')
85
    {
86
        $this->updateBrowser($object, $fields, $relationship, $positionAttribute);
87
    }
88
89
    /**
90
     * @param mixed $object
91
     * @param array $fields
92
     * @param string $browserName
93
     * @return void
94
     */
95
    public function updateRelatedBrowser($object, $fields, $browserName)
96
    {
97
        $object->saveRelated($fields['browsers'][$browserName] ?? [], $browserName);
98
    }
99
100
    /**
101
     * @param \A17\Twill\Models\Model $object
102
     * @param string $relation
103
     * @param string|null $routePrefix
104
     * @param string $titleKey
105
     * @param string|null $moduleName
106
     * @return array
107
     */
108
    public function getFormFieldsForBrowser($object, $relation, $routePrefix = null, $titleKey = 'title', $moduleName = null)
109
    {
110
        return $object->$relation->map(function ($relatedElement) use ($titleKey, $routePrefix, $relation, $moduleName) {
111
            return [
112
                'id' => $relatedElement->id,
113
                'name' => $relatedElement->titleInBrowser ?? $relatedElement->$titleKey,
114
                'edit' => moduleRoute($moduleName ?? $relation, $routePrefix ?? '', 'edit', $relatedElement->id),
115
                'endpointType' => $relatedElement->getMorphClass(),
116
            ] + (classHasTrait($relatedElement, HasMedias::class) ? [
0 ignored issues
show
Bug introduced by
The type A17\Twill\Repositories\Behaviors\HasMedias 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...
117
                'thumbnail' => $relatedElement->defaultCmsImage(['w' => 100, 'h' => 100]),
118
            ] : []);
119
        })->toArray();
120
    }
121
122
    /**
123
     * @param \A17\Twill\Models\Model $object
124
     * @param string $relation
125
     * @return array
126
     */
127
    public function getFormFieldsForRelatedBrowser($object, $relation)
128
    {
129
        return $object->getRelated($relation)->map(function ($relatedElement) {
130
            return ($relatedElement != null) ? [
131
                'id' => $relatedElement->id,
132
                'name' => $relatedElement->titleInBrowser ?? $relatedElement->title,
133
                'endpointType' => $relatedElement->getMorphClass(),
134
            ] + (empty($relatedElement->adminEditUrl) ? [] : [
135
                'edit' => $relatedElement->adminEditUrl,
136
            ]) + (classHasTrait($relatedElement, HasMedias::class) ? [
137
                'thumbnail' => $relatedElement->defaultCmsImage(['w' => 100, 'h' => 100]),
138
            ] : []) : [];
139
        })->reject(function ($item) {
140
            return empty($item);
141
        })->values()->toArray();
142
    }
143
144
        /**
145
     * Get all browser' detail info from the $browsers attribute. 
146
     * The missing information will be inferred by convention of Twill.
147
     *
148
     * @return Illuminate\Support\Collection
0 ignored issues
show
Bug introduced by
The type A17\Twill\Repositories\B...nate\Support\Collection was not found. Did you mean Illuminate\Support\Collection? If so, make sure to prefix the type with \.
Loading history...
149
     */
150 28
    protected function getBrowsers()
151
    {
152
        return collect($this->browsers)->map(function ($browser, $key) {
153
            $browserName = is_string($browser) ? $browser : $key;
154
            return [
155
                'relation' => !empty($browser['relation']) ? $browser['relation'] : $this->inferRelationFromBrowserName($browserName),
156
                'routePrefix' => isset($browser['routePrefix']) ? $browser['routePrefix'] : null,
157
                'titleKey' => !empty($browser['titleKey']) ? $browser['titleKey'] : 'title',
158
                'moduleName' => isset($browser['moduleName']) ? $browser['moduleName'] : null,
159
                'positionAttribute' => !empty($browser['positionAttribute']) ? $browser['positionAttribute'] : 'position',
160
                'browserName' => $browserName,
161
            ];
162 28
        })->values();
163
    }
164
165
    /**
166
     * The relation name shoud be lower camel case, ex. userGroup, contactOffice
167
     *
168
     * @param  string $browserName
169
     *
170
     * @return string
171
     */
172
    protected function inferRelationFromBrowserName(string $browserName): string
173
    {
174
        return Str::camel($browserName);
175
    }
176
}
177