Completed
Push — master ( 96b1a0...159412 )
by Alexandr
07:40
created

Component::saveLinkData()   D

Complexity

Conditions 9
Paths 3

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 18
nc 3
nop 1
dl 0
loc 26
rs 4.909
c 0
b 0
f 0
1
<?php
2
3
namespace Larrock\Core;
4
5
use Illuminate\Http\Request;
6
use Larrock\ComponentFeed\Models\Feed;
7
use Larrock\Core\Models\Seo;
8
use LarrockAdminSeo;
9
use LarrockFeed;
10
use Larrock\Core\Helpers\FormBuilder\FormCheckbox;
11
use Larrock\Core\Helpers\FormBuilder\FormInput;
12
use Larrock\Core\Helpers\FormBuilder\FormTextarea;
13
use Illuminate\Database\Eloquent\Model;
14
use JsValidator;
15
use Larrock\Core\Helpers\MessageLarrock;
16
use Larrock\Core\Models\Link;
17
use View;
18
19
class Component
20
{
21
    /** @var string */
22
    public $name;
23
24
    /** @var string */
25
    public $title;
26
27
    /** @var string */
28
    public $description;
29
30
    /** @var string */
31
    public $table;
32
33
    /** @var array */
34
    public $rows;
35
36
    public $customMediaConversions;
37
38
    /** @var Model */
39
    public $model;
40
41
    /** @var bool */
42
    public $active = TRUE;
43
    public $plugins_backend;
44
    public $plugins_front;
45
    public $settings;
46
    public $searchable;
47
48
    public $tabs;
49
    public $tabs_data;
50
51
    public $valid;
52
53
    /** @return Component */
54
    public function getConfig()
55
    {
56
        return $this;
57
    }
58
59
    /** @return string */
60
    public function getName()
61
    {
62
        return $this->name;
63
    }
64
65
    /** @return string */
66
    public function getTitle()
67
    {
68
        return $this->title;
69
    }
70
71
    /** @return Model */
72
    public function getModel()
73
    {
74
        return new $this->model;
75
    }
76
77
    /** @return string */
78
    public function getModelName()
79
    {
80
        return $this->model;
81
    }
82
83
    /** @return string */
84
    public function getTable()
85
    {
86
        return $this->table;
87
    }
88
89
    /** @return array */
90
    public function getRows()
91
    {
92
        return $this->rows;
93
    }
94
95
    public function getValid()
96
    {
97
        return self::_valid_construct($this);
98
    }
99
100
    /**
101
     * @param array $rows
102
     * @return array
103
     */
104
    public function addFillableUserRows(array $rows)
105
    {
106
        $fillable_rows = $rows;
107
        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...
108
            foreach ($this->rows as $key => $row){
109
                if($row->fillable){
110
                    $fillable_rows[] = $key;
111
                }
112
            }
113
        }
114
        return $fillable_rows;
115
    }
116
117
    /**
118
     * Получение fillable-полей модели компонента из его конфига
119
     * @return array
120
     */
121
    public function getFillableRows()
122
    {
123
        $fillable_rows = [];
124
        foreach ($this->rows as $key => $row){
125
            if($row->fillable){
126
                $fillable_rows[] = $key;
127
            }
128
        }
129
        return $fillable_rows;
130
    }
131
132
    /**
133
     * Добавление поля указания веса
134
     * @return $this
135
     */
136
    public function addPosition()
137
    {
138
        $row = new FormInput('position', 'Вес');
139
        $this->rows['position'] = $row->setTab('main', 'Дата, вес, активность')->setValid('integer')
140
            ->setDefaultValue(0)->setInTableAdminAjaxEditable()->setFillable()->setCssClassGroup('uk-width-1-3');
141
        return $this;
142
    }
143
144
    /**
145
     * Добавления поля для указания опубликованности
146
     * @return $this
147
     */
148
    public function addActive()
149
    {
150
        $row = new FormCheckbox('active', 'Опубликован');
151
        $this->rows['active'] = $row->setTab('main', 'Дата, вес, активность')
152
            ->setValid('integer|max:1')->setDefaultValue(1)->setInTableAdminAjaxEditable()->setFillable()
153
            ->setCssClassGroup('uk-width-1-3');
154
        return $this;
155
    }
156
157
    /**
158
     * Алиас для добавления полей веса и активности
159
     * @return $this
160
     */
161
    public function addPositionAndActive()
162
    {
163
        $this->addPosition();
164
        $this->addActive();
165
        return $this;
166
    }
167
168
    /**
169
     * Получение конфигурации компонента
170
     * Вывод в шаблон переменной $app с конфигом компонента, переменной $validator для JSValidation
171
     * @return $this
172
     */
173
    public function shareConfig()
174
    {
175
        $this->tabs = collect();
176
        $this->tabs_data = collect();
177
        View::share('app', $this);
178
        $this->valid = self::_valid_construct($this);
179
        View::share('validator', JsValidator::make($this->valid));
180
        return $this;
181
    }
182
183
    /**
184
     * Метод объявления использования middleware для компонентов.
185
     * Вызывается из конструктора класса контроллера компонента через $this->middleware(Компонент::combineFrontMiddlewares());
186
     * @param null $user_middlewares
187
     * @return array
188
     */
189
    public function combineFrontMiddlewares($user_middlewares = NULL)
190
    {
191
        $middleware = ['web', 'GetSeo'];
192
        if($config = config('larrock.middlewares.front')){
193
            $middleware = array_merge($middleware, $config);
194
        }
195
        if(file_exists(base_path(). '/vendor/fanamurov/larrock-menu')){
196
            $middleware[] = 'AddMenuFront';
197
        }
198
        if(file_exists(base_path(). '/vendor/fanamurov/larrock-blocks')){
199
            $middleware[] = 'AddBlocksTemplate';
200
        }
201
        if(file_exists(base_path(). '/vendor/fanamurov/larrock-discount')){
202
            $middleware[] = 'DiscountsShare';
203
        }
204
        if($user_middlewares){
205
            $middleware = array_merge($middleware, $user_middlewares);
206
        }
207
        return array_unique($middleware);
208
    }
209
210
    /**
211
     * Метод объявления использования middleware для компонентов.
212
     * Вызывается из конструктора класса контроллера компонента через $this->middleware(Компонент::combineAdminMiddlewares());
213
     * @param null $user_middlewares
214
     * @return array
215
     */
216
    public function combineAdminMiddlewares($user_middlewares = NULL)
217
    {
218
        $middleware = ['web', 'level:2', 'LarrockAdminMenu', 'SiteSearchAdmin'];
219
        if($config = config('larrock.middlewares.admin')){
220
            $middleware = array_merge($middleware, $config);
221
        }
222
        if($user_middlewares){
223
            $middleware = array_merge($middleware, $user_middlewares);
224
        }
225
        return array_unique($middleware);
226
    }
227
228
    /**
229
     * Подключение плагина SEO
230
     * @return $this
231
     */
232
    public function addPluginSeo()
233
    {
234
        $row = new FormInput('seo_title', 'Title материала');
235
        $this->rows['seo_title'] = $rows_plugin[] = $row->setTab('seo', 'Seo')->setValid('max:255')
0 ignored issues
show
Coding Style Comprehensibility introduced by
$rows_plugin was never initialized. Although not strictly required by PHP, it is generally a good practice to add $rows_plugin = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
236
            ->setTypo()->setHelp('По-умолчанию равно заголовку материала');
237
238
        $row = new FormInput('seo_description', 'Description материала');
239
        $this->rows['seo_description'] = $rows_plugin[] = $row->setTab('seo', 'Seo')->setValid('max:255')
240
            ->setTypo()->setHelp('По-умолчанию равно заголовку материала');
241
242
        $row = new FormTextarea('seo_keywords', 'Keywords материала');
243
        $this->rows['seo_keywords'] = $rows_plugin[] = $row->setTab('seo', 'Seo')->setValid('max:255')->setCssClass('not-editor uk-width-1-1');
244
245
        $this->plugins_backend['seo']['rows'] = $rows_plugin;
246
247
        $row = new FormInput('url', 'URL материала');
248
        $this->rows['url'] = $row->setTab('seo', 'SEO')
249
            ->setValid('max:155|required|unique:'. $this->table .',url,:id')->setCssClass('uk-width-1-1')->setFillable();
250
251
        return $this;
252
    }
253
254
    /**
255
     * Подключение плагина загрузки фото
256
     * @return $this
257
     */
258
    public function addPluginImages()
259
    {
260
        $this->plugins_backend['images'] = 'images';
261
        return $this;
262
    }
263
264
    /**
265
     * Метод для добавления в модель новых пресетов картинок для Medialibrary
266
     * @param array $conversions
267
     */
268
    public function addCustomMediaConversions(array $conversions)
269
    {
270
        $this->customMediaConversions = $conversions;
271
    }
272
273
    /**
274
     * Подключение плагина загрузки файлов
275
     * @return $this
276
     */
277
    public function addPluginFiles()
278
    {
279
        $this->plugins_backend['files'] = 'files';
280
        return $this;
281
    }
282
283
    /**
284
     * Плагин для генерации анонса новости для блока анонс новости
285
     * @param int $categoryAnons    ID категории с анонсами
286
     * @return $this
287
     */
288
    public function addAnonsToModule($categoryAnons)
289
    {
290
        $row = new FormCheckbox('anons_merge', 'Сгенерировать для анонса заголовок и ссылку на новость');
291
        $this->rows['anons_merge'] = $rows_plugin[] = $row->setTab('anons', 'Создать анонс');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$rows_plugin was never initialized. Although not strictly required by PHP, it is generally a good practice to add $rows_plugin = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
292
293
        $row = new FormTextarea('anons_description', 'Текст для анонса новости в модуле');
294
        $this->rows['anons_description'] = $rows_plugin[] = $row->setTab('anons', 'Создать анонс')->setTypo();
295
296
        $this->settings['anons_category'] = $categoryAnons;
297
        $this->plugins_backend['anons']['rows'] = $rows_plugin;
298
        return $this;
299
    }
300
301
    /**
302
     * Вспомогательный метод построения правил валидации из конфига полей компонента
303
     * @param array|object $config
304
     * @param string $action create|update
305
     * @param null|string|integer   $id
306
     * @return array
307
     */
308
    public static function _valid_construct($config, $action = 'create', $id = NULL)
309
    {
310
        $rules = array();
311
        if(isset($config->rows)){
312
            foreach($config->rows as $rows_value){
313
                if( !empty($rows_value->valid)){
314
                    $rules[$rows_value->name] = $rows_value->valid;
315
                    if($action === 'update'){
316
                        $rules[$rows_value->name] = str_replace(':id', $id, $rules[$rows_value->name]);
317
                    }else{
318
                        $rules[$rows_value->name] = str_replace(',:id', '', $rules[$rows_value->name]);
319
                    }
320
                }
321
            }
322
        }
323
        return $rules;
324
    }
325
326
    /**
327
     * Вывод данных полей компонента для табов
328
     * @param Model $data
329
     * @return $this
330
     */
331
    public function tabbable($data)
332
    {
333
        if($this->plugins_backend){
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->plugins_backend of type array<string,string> 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...
334
            $this->addDataPlugins($data);
335
        }
336
337
        $this->tabs = collect();
338
        foreach($this->rows as $row_value){
339
            $this->tabs->put(key($row_value->tab), current($row_value->tab));
340
        }
341
        foreach($this->tabs as $tab_key => $tab_value){
342
            $render = '';
343
            foreach($this->rows as $row_value){
344
                $class_name = \get_class($row_value);
345
                $load_class = new $class_name($row_value->name, $row_value->title);
346
347
                if(key($row_value->tab) === $tab_key){
348
                    if(method_exists($load_class, 'render')){
349
                        $render .= $load_class->render($row_value, $data);
350
                    }else{
351
                        $this->tabs_data->put($tab_key, '<p>'. $class_name .' не определен для отрисовки</p>');
352
                    }
353
                }
354
            }
355
            $this->tabs_data->put($tab_key, $render);
356
        }
357
        return $this;
358
    }
359
360
    /**
361
     * Присоединяем данные от плагинов
362
     * @param Model $data
363
     */
364
    public function addDataPlugins($data)
365
    {
366
        if($this->plugins_backend && \is_array($this->plugins_backend)){
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->plugins_backend of type array<string,string> 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...
367
            foreach ($this->plugins_backend as $key_plugin => $value_plugin){
368
                if($key_plugin === 'seo' && $plugin_data = $data->getSeo){
369
                    foreach ($this->rows as $key => $value){
370
                        if($value->name === 'seo_title' || $value->name === 'seo_description' || $value->name === 'seo_keywords'){
371
                            $this->rows[$key]->default = $plugin_data->{$value->name};
372
                        }
373
                    }
374
                }
375
            }
376
        }
377
    }
378
379
    /**
380
     * Перезапись конфига компонента (например внутри контроллера)
381
     * @param $option
382
     * @param $config
383
     * @return $this
384
     */
385
    public function overrideComponent($option, $config)
386
    {
387
        $this->{$option} = $config;
388
        return $this;
389
    }
390
391
    /**
392
     * Разрешить поиск по материалам компонента
393
     * @return $this
394
     */
395
    public function isSearchable()
396
    {
397
        $this->searchable = TRUE;
398
        return $this;
399
    }
400
401
    /**
402
     * Формирование пунктов меню компонента в админке
403
     * @return string
404
     */
405
    public function renderAdminMenu()
406
    {
407
        return '';
408
    }
409
410
    /**
411
     * Метод встаивания данных компонента в карту сайта sitemap.xml
412
     * @return null
413
     */
414
    public function createSitemap()
415
    {
416
        return NULL;
417
    }
418
419
    /**
420
     * Метод встаивания данных компонента в rss-feed
421
     * @return null
422
     */
423
    public function createRSS()
424
    {
425
        return NULL;
426
    }
427
428
    /**
429
     * Данные для поиска по материалам компонента
430
     * @param null|bool $admin Если TRUE - для поиска будут доступны вообще все элементы (не только опубликованные)
431
     * @return null
432
     */
433
    public function search($admin)
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...
434
    {
435
        return NULL;
436
    }
437
}