Passed
Push — master ( 228108...ad6a40 )
by Alexandr
02:35
created

Component::search()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Larrock\Core;
4
5
use View;
6
use JsValidator;
0 ignored issues
show
Bug introduced by
The type JsValidator 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...
7
use Illuminate\Support\Collection;
8
use Illuminate\Database\Eloquent\Model;
9
use Larrock\Core\Plugins\PluginSeoTrait;
10
use Larrock\Core\Plugins\PluginAnonsTrait;
11
use Larrock\Core\Helpers\FormBuilder\FBElement;
12
use Larrock\Core\Helpers\FormBuilder\FormInput;
13
use Larrock\Core\Helpers\FormBuilder\FormCheckbox;
14
use Larrock\Core\ComponentTraits\ComponentSearchTrait;
15
16
class Component
17
{
18
    use PluginSeoTrait, PluginAnonsTrait, ComponentSearchTrait;
0 ignored issues
show
introduced by
The trait Larrock\Core\ComponentTraits\ComponentSearchTrait requires some properties which are not provided by Larrock\Core\Component: $getCategory, $getCategoryActive, $full_url, $id, $admin_url
Loading history...
19
20
    /** @var string */
21
    public $name;
22
23
    /** @var string */
24
    public $title;
25
26
    /** @var string */
27
    public $description;
28
29
    /** @var string */
30
    public $table;
31
32
    /** @var array */
33
    public $rows = [];
34
35
    /** @var array */
36
    public $customMediaConversions;
37
38
    /** @var Model */
39
    public $model;
40
41
    /** @var bool */
42
    public $active = true;
43
44
    /** @var array */
45
    public $plugins_backend;
46
47
    /** @var array */
48
    public $plugins_front;
49
50
    /** @var array */
51
    public $settings;
52
53
    /** @var array|Collection */
54
    public $tabs;
55
56
    /** @var array|Collection */
57
    public $tabs_data;
58
59
    /** @var mixed */
60
    public $valid;
61
62
    /** @return Component */
63
    public function getConfig()
64
    {
65
        return $this;
66
    }
67
68
    /** @return string */
69
    public function getName() :string
70
    {
71
        return $this->name;
72
    }
73
74
    /** @return string */
75
    public function getTitle() :string
76
    {
77
        return $this->title;
78
    }
79
80
    /** @return Model */
81
    public function getModel()
82
    {
83
        return new $this->model;
84
    }
85
86
    /** @return string */
87
    public function getModelName()
88
    {
89
        return $this->model;
90
    }
91
92
    /** @return string */
93
    public function getTable() :string
94
    {
95
        return $this->table;
96
    }
97
98
    /**
99
     * @param FBElement $FBElement
100
     * @return Component
101
     */
102
    public function setRow($FBElement)
103
    {
104
        $this->rows[$FBElement->name] = $FBElement;
105
106
        return $this;
107
    }
108
109
    /** @return array */
110
    public function getRows()
111
    {
112
        return $this->rows;
113
    }
114
115
    /**
116
     * Получение правил валидации.
117
     *
118
     * @param null|int $edit
119
     * @return array
120
     */
121
    public function getValid($edit = null)
122
    {
123
        $rules = [];
124
        foreach ($this->rows as $rows_value) {
125
            if (! empty($rows_value->valid)) {
126
                $rules[$rows_value->name] = $rows_value->valid;
127
                if ($edit && $rows_value->name === 'url') {
0 ignored issues
show
Bug Best Practice introduced by
The expression $edit of type null|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
128
                    $rules[$rows_value->name] = str_replace(
129
                        'unique:'.$this->table,
130
                        'unique:'.$this->table.','.$rows_value->name.','.$edit,
131
                        $rules[$rows_value->name]
132
                    );
133
                }
134
            }
135
        }
136
137
        return $rules;
138
    }
139
140
    /**
141
     * @param array $rows
142
     * @return array
143
     */
144
    public function addFillableUserRows(array $rows)
145
    {
146
        $fillable_rows = $rows;
147
        if ($this->rows && \is_array($this->rows)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->rows of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
148
            foreach ($this->rows as $key => $row) {
149
                if ($row->fillable) {
150
                    $fillable_rows[] = $key;
151
                }
152
            }
153
        }
154
155
        return $fillable_rows;
156
    }
157
158
    /**
159
     * Получение fillable-полей модели компонента из его конфига.
160
     * @return array
161
     */
162
    public function getFillableRows()
163
    {
164
        $fillable_rows = [];
165
        foreach ($this->rows as $key => $row) {
166
            if ($row->fillable) {
167
                $fillable_rows[] = $key;
168
            }
169
        }
170
171
        return $fillable_rows;
172
    }
173
174
    /**
175
     * Добавление поля указания веса.
176
     * @return $this
177
     */
178
    public function addPosition()
179
    {
180
        $row = new FormInput('position', 'Вес');
181
        $this->rows['position'] = $row->setTab('main', 'Дата, вес, активность')->setValid('integer|nullable')
182
            ->setDefaultValue(0)->setInTableAdminEditable()->setFillable()->setCssClassGroup('uk-width-1-3');
183
184
        return $this;
185
    }
186
187
    /**
188
     * Добавления поля для указания опубликованности.
189
     * @return $this
190
     */
191
    public function addActive()
192
    {
193
        $row = new FormCheckbox('active', 'Опубликован');
194
        $this->rows['active'] = $row->setTab('main', 'Дата, вес, активность')
195
            ->setValid('integer|max:1|nullable')->setDefaultValue(1)->setInTableAdminEditable()->setFillable()
196
            ->setCssClassGroup('uk-width-1-3');
197
198
        return $this;
199
    }
200
201
    /**
202
     * Алиас для добавления полей веса и активности.
203
     * @return $this
204
     */
205
    public function addPositionAndActive()
206
    {
207
        $this->addPosition();
208
        $this->addActive();
209
210
        return $this;
211
    }
212
213
    /**
214
     * Получение конфигурации компонента
215
     * Вывод в шаблон переменной $app с конфигом компонента, переменной $validator для JSValidation.
216
     * @return $this
217
     */
218
    public function shareConfig()
219
    {
220
        $this->tabs = collect();
221
        $this->tabs_data = collect();
222
        View::share('package', $this);
0 ignored issues
show
Bug introduced by
'package' of type string is incompatible with the type array expected by parameter $| of Illuminate\Support\Facades\View::share(). ( Ignorable by Annotation )

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

222
        View::share(/** @scrutinizer ignore-type */ 'package', $this);
Loading history...
223
        $this->valid = $this->getValid();
224
        View::share('validator', JsValidator::make($this->getValid()));
225
226
        return $this;
227
    }
228
229
    /**
230
     * Метод объявления использования middleware для компонентов.
231
     * Вызывается из конструктора класса контроллера компонента через $this->middleware(Компонент::combineFrontMiddlewares());.
232
     * @param null $user_middlewares
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $user_middlewares is correct as it would always require null to be passed?
Loading history...
233
     * @return array
234
     */
235
    public function combineFrontMiddlewares($user_middlewares = null)
236
    {
237
        $middleware = ['web', 'GetSeo', 'AddMenuFront', 'AddBlocksTemplate', 'ContactCreateTemplate'];
238
        if ($config = config('larrock.middlewares.front')) {
239
            $middleware = array_merge($middleware, $config);
240
        }
241
        if (file_exists(base_path().'/vendor/fanamurov/larrock-discount')) {
242
            $middleware[] = 'DiscountsShare';
243
        }
244
        if ($user_middlewares) {
245
            $middleware = array_merge($middleware, $user_middlewares);
246
        }
247
248
        return array_unique($middleware);
249
    }
250
251
    /**
252
     * Метод объявления использования middleware для компонентов.
253
     * Вызывается из конструктора класса контроллера компонента через $this->middleware(Компонент::combineAdminMiddlewares());.
254
     * @param null $user_middlewares
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $user_middlewares is correct as it would always require null to be passed?
Loading history...
255
     * @return array
256
     */
257
    public function combineAdminMiddlewares($user_middlewares = null)
258
    {
259
        $middleware = ['web', 'level:2', 'LarrockAdminMenu'];
260
        if ($config = config('larrock.middlewares.admin')) {
261
            $middleware = array_merge($middleware, $config);
262
        }
263
        if ($user_middlewares) {
264
            $middleware = array_merge($middleware, $user_middlewares);
265
        }
266
267
        return array_unique($middleware);
268
    }
269
270
    /**
271
     * Подключение плагина загрузки фото.
272
     * @return $this
273
     */
274
    public function addPluginImages()
275
    {
276
        $this->plugins_backend['images'] = 'images';
277
278
        return $this;
279
    }
280
281
    /**
282
     * Метод для добавления в модель новых пресетов картинок для Medialibrary.
283
     * @param array $conversions
284
     */
285
    public function addCustomMediaConversions(array $conversions)
286
    {
287
        $this->customMediaConversions = $conversions;
288
    }
289
290
    /**
291
     * Подключение плагина загрузки файлов.
292
     * @return $this
293
     */
294
    public function addPluginFiles()
295
    {
296
        $this->plugins_backend['files'] = 'files';
297
298
        return $this;
299
    }
300
301
    /**
302
     * Вывод данных полей компонента для табов.
303
     * @param Model $data
304
     * @return $this
305
     */
306
    public function tabbable($data)
307
    {
308
        if (isset($this->plugins_backend['seo']) && $plugin_data = $data->getSeo) {
309
            //Присоединяем данные от плагинов
310
            $this->rows['seo_title']->default = $plugin_data->seo_title;
0 ignored issues
show
Bug introduced by
The property seo_title does not seem to exist on Illuminate\Database\Eloquent\Relations\Relation.
Loading history...
Bug introduced by
The property seo_title does not seem to exist on Illuminate\Database\Eloquent\Builder.
Loading history...
311
            $this->rows['seo_description']->default = $plugin_data->seo_description;
0 ignored issues
show
Bug introduced by
The property seo_description does not seem to exist on Illuminate\Database\Eloquent\Relations\Relation.
Loading history...
Bug introduced by
The property seo_description does not seem to exist on Illuminate\Database\Eloquent\Builder.
Loading history...
312
            $this->rows['seo_keywords']->default = $plugin_data->seo_keywords;
0 ignored issues
show
Bug introduced by
The property seo_keywords does not seem to exist on Illuminate\Database\Eloquent\Builder.
Loading history...
Bug introduced by
The property seo_keywords does not seem to exist on Illuminate\Database\Eloquent\Relations\Relation.
Loading history...
313
        }
314
315
        $this->tabs = collect();
316
        $this->tabs_data = collect();
317
        foreach ($this->rows as $row_value) {
318
            $this->tabs->put(key($row_value->tab), current($row_value->tab));
319
320
            if (! isset($this->tabs_data[key($row_value->tab)])) {
321
                $this->tabs_data->put(key($row_value->tab), $row_value->setData($data));
322
            } else {
323
                $this->tabs_data[key($row_value->tab)] .= $row_value->setData($data);
324
            }
325
        }
326
327
        return $this;
328
    }
329
330
    /**
331
     * Перезапись конфига компонента (например внутри контроллера).
332
     * @param $option
333
     * @param $config
334
     * @return $this
335
     */
336
    public function overrideComponent($option, $config)
337
    {
338
        $this->{$option} = $config;
339
340
        return $this;
341
    }
342
343
    /**
344
     * Перезапись конфига поля компонента (например внутри контроллера).
345
     * @param string $key
346
     * @param FBElement $row
347
     * @return $this
348
     */
349
    public function overrideRow($key, $row)
350
    {
351
        $this->removeRow($key);
352
353
        return $this->setRow($row);
354
    }
355
356
    /**
357
     * Удаление поля из компонента (например внутри контроллера).
358
     * @param string $key
359
     * @return $this
360
     */
361
    public function removeRow($key)
362
    {
363
        if (array_key_exists($key, $this->rows)) {
364
            unset($this->rows[$key]);
365
        }
366
367
        return $this;
368
    }
369
370
    /**
371
     * Формирование пунктов меню компонента в админке.
372
     * @return string
373
     */
374
    public function renderAdminMenu()
375
    {
376
        return '';
377
    }
378
379
    /**
380
     * Метод встаивания данных компонента в карту сайта sitemap.xml.
381
     * @return null
382
     */
383
    public function createSitemap()
384
    {
385
        return null;
386
    }
387
388
    /**
389
     * Метод встаивания данных компонента в rss-feed.
390
     * @return null
391
     */
392
    public function createRSS()
393
    {
394
        return null;
395
    }
396
}
397