Completed
Push — master ( f90b07...326b8f )
by Alexandr
08:01
created

Component::removeRow()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Larrock\Core;
4
5
use View;
6
use JsValidator;
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
15
class Component
16
{
17
    use PluginSeoTrait, PluginAnonsTrait;
18
19
    /** @var string */
20
    public $name;
21
22
    /** @var string */
23
    public $title;
24
25
    /** @var string */
26
    public $description;
27
28
    /** @var string */
29
    public $table;
30
31
    /** @var array */
32
    public $rows;
33
34
    /** @var array */
35
    public $customMediaConversions;
36
37
    /** @var Model */
38
    public $model;
39
40
    /** @var bool */
41
    public $active = true;
42
43
    /** @var array */
44
    public $plugins_backend;
45
46
    /** @var array */
47
    public $plugins_front;
48
49
    /** @var array */
50
    public $settings;
51
52
    /** @var null|bool */
53
    public $searchable;
54
55
    /** @var array|Collection */
56
    public $tabs;
57
58
    /** @var array|Collection */
59
    public $tabs_data;
60
61
    /** @var mixed */
62
    public $valid;
63
64
    /** @return Component */
65
    public function getConfig()
66
    {
67
        return $this;
68
    }
69
70
    /** @return string */
71
    public function getName() :string
72
    {
73
        return $this->name;
74
    }
75
76
    /** @return string */
77
    public function getTitle() :string
78
    {
79
        return $this->title;
80
    }
81
82
    /** @return Model */
83
    public function getModel()
84
    {
85
        return new $this->model;
86
    }
87
88
    /** @return string */
89
    public function getModelName()
90
    {
91
        return $this->model;
92
    }
93
94
    /** @return string */
95
    public function getTable() :string
96
    {
97
        return $this->table;
98
    }
99
100
    /**
101
     * @param FBElement $FBElement
102
     * @return Component
103
     */
104
    public function setRow($FBElement)
105
    {
106
        $this->rows[$FBElement->name] = $FBElement;
107
108
        return $this;
109
    }
110
111
    /** @return array */
112
    public function getRows()
113
    {
114
        return $this->rows;
115
    }
116
117
    public function getValid()
118
    {
119
        return self::_valid_construct($this);
120
    }
121
122
    /**
123
     * @param array $rows
124
     * @return array
125
     */
126
    public function addFillableUserRows(array $rows)
127
    {
128
        $fillable_rows = $rows;
129
        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...
130
            foreach ($this->rows as $key => $row) {
131
                if ($row->fillable) {
132
                    $fillable_rows[] = $key;
133
                }
134
            }
135
        }
136
137
        return $fillable_rows;
138
    }
139
140
    /**
141
     * Получение fillable-полей модели компонента из его конфига.
142
     * @return array
143
     */
144
    public function getFillableRows()
145
    {
146
        $fillable_rows = [];
147
        foreach ($this->rows as $key => $row) {
148
            if ($row->fillable) {
149
                $fillable_rows[] = $key;
150
            }
151
        }
152
153
        return $fillable_rows;
154
    }
155
156
    /**
157
     * Добавление поля указания веса.
158
     * @return $this
159
     */
160
    public function addPosition()
161
    {
162
        $row = new FormInput('position', 'Вес');
163
        $this->rows['position'] = $row->setTab('main', 'Дата, вес, активность')->setValid('integer')
164
            ->setDefaultValue(0)->setInTableAdminEditable()->setFillable()->setCssClassGroup('uk-width-1-3');
165
166
        return $this;
167
    }
168
169
    /**
170
     * Добавления поля для указания опубликованности.
171
     * @return $this
172
     */
173
    public function addActive()
174
    {
175
        $row = new FormCheckbox('active', 'Опубликован');
176
        $this->rows['active'] = $row->setTab('main', 'Дата, вес, активность')
177
            ->setValid('integer|max:1')->setDefaultValue(1)->setInTableAdminEditable()->setFillable()
178
            ->setCssClassGroup('uk-width-1-3');
179
180
        return $this;
181
    }
182
183
    /**
184
     * Алиас для добавления полей веса и активности.
185
     * @return $this
186
     */
187
    public function addPositionAndActive()
188
    {
189
        $this->addPosition();
190
        $this->addActive();
191
192
        return $this;
193
    }
194
195
    /**
196
     * Получение конфигурации компонента
197
     * Вывод в шаблон переменной $app с конфигом компонента, переменной $validator для JSValidation.
198
     * @return $this
199
     */
200
    public function shareConfig()
201
    {
202
        $this->tabs = collect();
203
        $this->tabs_data = collect();
204
        View::share('app', $this);
205
        $this->valid = self::_valid_construct($this);
206
        View::share('validator', JsValidator::make($this->valid));
207
208
        return $this;
209
    }
210
211
    /**
212
     * Метод объявления использования middleware для компонентов.
213
     * Вызывается из конструктора класса контроллера компонента через $this->middleware(Компонент::combineFrontMiddlewares());.
214
     * @param null $user_middlewares
215
     * @return array
216
     */
217
    public function combineFrontMiddlewares($user_middlewares = null)
218
    {
219
        $middleware = ['web', 'GetSeo', 'AddMenuFront', 'AddBlocksTemplate', 'ContactCreateTemplate'];
220
        if ($config = config('larrock.middlewares.front')) {
221
            $middleware = array_merge($middleware, $config);
222
        }
223
        if (file_exists(base_path().'/vendor/fanamurov/larrock-discount')) {
224
            $middleware[] = 'DiscountsShare';
225
        }
226
        if ($user_middlewares) {
227
            $middleware = array_merge($middleware, $user_middlewares);
228
        }
229
230
        return array_unique($middleware);
231
    }
232
233
    /**
234
     * Метод объявления использования middleware для компонентов.
235
     * Вызывается из конструктора класса контроллера компонента через $this->middleware(Компонент::combineAdminMiddlewares());.
236
     * @param null $user_middlewares
237
     * @return array
238
     */
239
    public function combineAdminMiddlewares($user_middlewares = null)
240
    {
241
        $middleware = ['web', 'level:2', 'LarrockAdminMenu'];
242
        if ($config = config('larrock.middlewares.admin')) {
243
            $middleware = array_merge($middleware, $config);
244
        }
245
        if ($user_middlewares) {
246
            $middleware = array_merge($middleware, $user_middlewares);
247
        }
248
249
        return array_unique($middleware);
250
    }
251
252
    /**
253
     * Подключение плагина загрузки фото.
254
     * @return $this
255
     */
256
    public function addPluginImages()
257
    {
258
        $this->plugins_backend['images'] = 'images';
259
260
        return $this;
261
    }
262
263
    /**
264
     * Метод для добавления в модель новых пресетов картинок для Medialibrary.
265
     * @param array $conversions
266
     */
267
    public function addCustomMediaConversions(array $conversions)
268
    {
269
        $this->customMediaConversions = $conversions;
270
    }
271
272
    /**
273
     * Подключение плагина загрузки файлов.
274
     * @return $this
275
     */
276
    public function addPluginFiles()
277
    {
278
        $this->plugins_backend['files'] = 'files';
279
280
        return $this;
281
    }
282
283
    /**
284
     * Вспомогательный метод построения правил валидации из конфига полей компонента.
285
     * @param array|object $config
286
     * @param string $action create|update
287
     * @param null|string|int   $id
288
     * @return array
289
     */
290
    public static function _valid_construct($config, $action = 'create', $id = null)
291
    {
292
        $rules = [];
293
        if (isset($config->rows)) {
294
            foreach ($config->rows as $rows_value) {
295
                if (! empty($rows_value->valid)) {
296
                    $rules[$rows_value->name] = $rows_value->valid;
297
                    if ($action === 'update') {
298
                        $rules[$rows_value->name] = str_replace(':id', $id, $rules[$rows_value->name]);
299
                    } else {
300
                        $rules[$rows_value->name] = str_replace(',:id', '', $rules[$rows_value->name]);
301
                    }
302
                }
303
            }
304
        }
305
306
        return $rules;
307
    }
308
309
    /**
310
     * Вывод данных полей компонента для табов.
311
     * @param Model $data
312
     * @return $this
313
     */
314
    public function tabbable($data)
315
    {
316
        if (isset($this->plugins_backend['seo']) && $plugin_data = $data->getSeo) {
317
            //Присоединяем данные от плагинов
318
            $this->rows['seo_title']->default = $plugin_data->seo_title;
319
            $this->rows['seo_description']->default = $plugin_data->seo_description;
320
            $this->rows['seo_keywords']->default = $plugin_data->seo_keywords;
321
        }
322
323
        $this->tabs = collect();
324
        $this->tabs_data = collect();
325
        foreach ($this->rows as $row_value) {
326
            $this->tabs->put(key($row_value->tab), current($row_value->tab));
327
328
            if (! isset($this->tabs_data[key($row_value->tab)])) {
329
                $this->tabs_data->put(key($row_value->tab), $row_value->setData($data));
330
            } else {
331
                $this->tabs_data[key($row_value->tab)] .= $row_value->setData($data);
332
            }
333
        }
334
335
        return $this;
336
    }
337
338
    /**
339
     * Перезапись конфига компонента (например внутри контроллера).
340
     * @param $option
341
     * @param $config
342
     * @return $this
343
     */
344
    public function overrideComponent($option, $config)
345
    {
346
        $this->{$option} = $config;
347
348
        return $this;
349
    }
350
351
    /**
352
     * Перезапись конфига поля компонента (например внутри контроллера).
353
     * @param string $key
354
     * @param FBElement $row
355
     * @return $this
356
     */
357
    public function overrideRow($key, $row)
358
    {
359
        if(isset($this->rows{$key})){
360
            unset($this->rows{$key});
361
        }
362
363
        return $this->setRow($row);
364
    }
365
366
    /**
367
     * Удаление поля из компонента (например внутри контроллера).
368
     * @param string $key
369
     * @return $this
370
     */
371
    public function removeRow($key)
372
    {
373
        unset($this->rows[$key]);
374
375
        return $this;
376
    }
377
378
    /**
379
     * Разрешить поиск по материалам компонента.
380
     * @return $this
381
     */
382
    public function isSearchable()
383
    {
384
        $this->searchable = true;
385
386
        return $this;
387
    }
388
389
    /**
390
     * Формирование пунктов меню компонента в админке.
391
     * @return string
392
     */
393
    public function renderAdminMenu()
394
    {
395
        return '';
396
    }
397
398
    /**
399
     * Метод встаивания данных компонента в карту сайта sitemap.xml.
400
     * @return null
401
     */
402
    public function createSitemap()
403
    {
404
        return null;
405
    }
406
407
    /**
408
     * Метод встаивания данных компонента в rss-feed.
409
     * @return null
410
     */
411
    public function createRSS()
412
    {
413
        return null;
414
    }
415
416
    /**
417
     * Данные для поиска по материалам компонента.
418
     * @param null|bool $admin Если TRUE - для поиска будут доступны вообще все элементы (не только опубликованные)
419
     * @return null
420
     */
421
    public function search($admin = null)
0 ignored issues
show
Unused Code introduced by
The parameter $admin is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
422
    {
423
        return null;
424
    }
425
}
426