Passed
Pull Request — master (#542)
by
unknown
05:00
created

HandleBrowsers::getBrowsers()   B

Complexity

Conditions 8
Paths 1

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 43.0556

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 12
nc 1
nop 0
dl 0
loc 16
ccs 2
cts 11
cp 0.1818
crap 43.0556
rs 8.4444
c 1
b 0
f 0
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
            $moduleName = !empty($browser['moduleName']) ? $browser['moduleName'] : $this->inferModuleNameFromBrowserName($browserName);
155
            
156
            return [
157
                'relation' => !empty($browser['relation']) ? $browser['relation'] : $this->inferRelationFromBrowserName($browserName),
158
                'routePrefix' => isset($browser['routePrefix']) ? $browser['routePrefix'] : null,
159
                'titleKey' => !empty($browser['titleKey']) ? $browser['titleKey'] : 'title',
160
                'moduleName' => $moduleName,
161
                'model' => !empty($browser['model']) ? $browser['model'] : $this->inferModelFromModuleName($moduleName),
162
                'positionAttribute' => !empty($browser['positionAttribute']) ? $browser['positionAttribute'] : 'position',
163
                'browserName' => $browserName,
164
            ];
165 28
        })->values();
166
    }
167
168
    /**
169
     * The relation name shoud be lower camel case, ex. userGroup, contactOffice
170
     *
171
     * @param  string $browserName
172
     *
173
     * @return string
174
     */
175
    protected function inferRelationFromBrowserName(string $browserName): string
176
    {
177
        return Str::camel($browserName);
178
    }
179
180
    /**
181
     * The model name should be singular upper camel case, ex. User, ArticleType
182
     *
183
     * @param  string $moduleName
184
     *
185
     * @return string
186
     */
187
    protected function inferModelFromModuleName(string $moduleName): string
188
    {
189
        return Str::studly(Str::singular($moduleName));
190
    }
191
192
    /**
193
     * The module name should be plural lower camel case 
194
     *
195
     * @param  mixed $string
196
     * @param  mixed $browserName
197
     *
198
     * @return string
199
     */
200
    protected function inferModuleNameFromBrowserName(string $browserName): string
201
    {
202
        return Str::camel(Str::plural($browserName));
203
    }
204
}
205