/
Component.php
executable file
·644 lines (577 loc) · 23 KB
/
Component.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
<?php
namespace Larrock\Core;
use Illuminate\Http\Request;
use Larrock\ComponentAdminSeo\Facades\LarrockSeo;
use LarrockFeed;
use Larrock\Core\Helpers\FormBuilder\FormCheckbox;
use Larrock\Core\Helpers\FormBuilder\FormInput;
use Larrock\Core\Helpers\FormBuilder\FormTextarea;
use Illuminate\Database\Eloquent\Model;
use JsValidator;
use Larrock\Core\Helpers\MessageLarrock;
use Larrock\Core\Models\Link;
use View;
use Config;
class Component
{
/** @var string */
public $name;
/** @var string */
public $title;
/** @var string */
public $description;
/** @var string */
public $table;
/** @var array */
public $rows;
public $customMediaConversions;
/** @var Model */
public $model;
/** @var bool */
public $active = TRUE;
public $plugins_backend;
public $plugins_front;
public $settings;
public $searchable;
public $tabs;
public $tabs_data;
public $valid;
/** @return Component */
public function getConfig()
{
return $this;
}
/** @return string */
public function getName()
{
return $this->name;
}
/** @return string */
public function getTitle()
{
return $this->title;
}
/** @return Model */
public function getModel()
{
return new $this->model;
}
/** @return string */
public function getModelName()
{
return $this->model;
}
/** @return string */
public function getTable()
{
return $this->table;
}
/** @return array */
public function getRows()
{
return $this->rows;
}
public function getValid()
{
return self::_valid_construct($this);
}
/**
* @param array $rows
* @return array
*/
public function addFillableUserRows(array $rows)
{
$fillable_rows = $rows;
if($this->rows && \is_array($this->rows)){
foreach ($this->rows as $key => $row){
if($row->fillable){
$fillable_rows[] = $key;
}
}
}
return $fillable_rows;
}
/**
* Получение fillable-полей модели компонента из его конфига
* @return array
*/
public function getFillableRows()
{
$fillable_rows = [];
foreach ($this->rows as $key => $row){
if($row->fillable){
$fillable_rows[] = $key;
}
}
return $fillable_rows;
}
/**
* Добавление поля указания веса
* @return $this
*/
public function addPosition()
{
$row = new FormInput('position', 'Вес');
$this->rows['position'] = $row->setTab('main', 'Дата, вес, активность')->setValid('integer')
->setDefaultValue(0)->setInTableAdminAjaxEditable()->setFillable()->setCssClassGroup('uk-width-1-3');
return $this;
}
/**
* Добавления поля для указания опубликованности
* @return $this
*/
public function addActive()
{
$row = new FormCheckbox('active', 'Опубликован');
$this->rows['active'] = $row->setTab('main', 'Дата, вес, активность')
->setValid('integer|max:1')->setDefaultValue(1)->setInTableAdminAjaxEditable()->setFillable()
->setCssClassGroup('uk-width-1-3');
return $this;
}
/**
* Алиас для добавления полей веса и активности
* @return $this
*/
public function addPositionAndActive()
{
$this->addPosition();
$this->addActive();
return $this;
}
/**
* Получение конфигурации компонента
* Вывод в шаблон переменной $app с конфигом компонента, переменной $validator для JSValidation
* @return $this
*/
public function shareConfig()
{
$this->tabs = collect();
$this->tabs_data = collect();
View::share('app', $this);
$this->valid = self::_valid_construct($this);
View::share('validator', JsValidator::make($this->valid));
return $this;
}
/**
* Метод объявления использования middleware для компонентов.
* Вызывается из конструктора класса контроллера компонента через $this->middleware(Компонент::combineFrontMiddlewares());
* @param null $user_middlewares
* @return array
*/
public function combineFrontMiddlewares($user_middlewares = NULL)
{
$middleware = ['web', 'GetSeo'];
if($config = config('larrock.middlewares.front')){
$middleware = array_merge($middleware, $config);
}
if(file_exists(base_path(). '/vendor/fanamurov/larrock-menu')){
$middleware[] = 'AddMenuFront';
}
if(file_exists(base_path(). '/vendor/fanamurov/larrock-blocks')){
$middleware[] = 'AddBlocksTemplate';
}
if(file_exists(base_path(). '/vendor/fanamurov/larrock-discount')){
$middleware[] = 'DiscountsShare';
}
if($user_middlewares){
$middleware = array_merge($middleware, $user_middlewares);
}
return array_unique($middleware);
}
/**
* Метод объявления использования middleware для компонентов.
* Вызывается из конструктора класса контроллера компонента через $this->middleware(Компонент::combineAdminMiddlewares());
* @param null $user_middlewares
* @return array
*/
public function combineAdminMiddlewares($user_middlewares = NULL)
{
$middleware = ['web', 'level:2', 'LarrockAdminMenu', 'SaveAdminPluginsData', 'SiteSearchAdmin'];
if($config = config('larrock.middlewares.admin')){
$middleware = array_merge($middleware, $config);
}
if($user_middlewares){
$middleware = array_merge($middleware, $user_middlewares);
}
return array_unique($middleware);
}
/**
* Используется через SaveAdminPluginsData Middleware (Core)
* @param $request
* @throws \Exception
*/
public function savePluginsData($request)
{
$this->savePluginSeoData($request);
$this->savePluginAnonsToModuleData($request);
$this->saveLinkData($request);
}
/**
* Подключение плагина SEO
* @return $this
*/
public function addPluginSeo()
{
$row = new FormInput('seo_title', 'Title материала');
$this->rows['seo_title'] = $rows_plugin[] = $row->setTab('seo', 'Seo')->setValid('max:255')
->setTypo()->setHelp('По-умолчанию равно заголовку материала');
$row = new FormInput('seo_description', 'Description материала');
$this->rows['seo_description'] = $rows_plugin[] = $row->setTab('seo', 'Seo')->setValid('max:255')
->setTypo()->setHelp('По-умолчанию равно заголовку материала');
$row = new FormTextarea('seo_keywords', 'Keywords материала');
$this->rows['seo_keywords'] = $rows_plugin[] = $row->setTab('seo', 'Seo')->setValid('max:255')->setCssClass('not-editor uk-width-1-1');
$this->plugins_backend['seo']['rows'] = $rows_plugin;
$row = new FormInput('url', 'URL материала');
$this->rows['url'] = $row->setTab('seo', 'SEO')
->setValid('max:155|required|unique:'. $this->table .',url,:id')->setCssClass('uk-width-1-1')->setFillable();
return $this;
}
/**
* @param Request|\Illuminate\Http\Request $request
* @return bool
*/
public function savePluginSeoData(Request $request)
{
if( !$request->has('_jsvalidation')
&& ($request->has('seo_title') || $request->get('seo_description') || $request->get('seo_seo_keywords'))
&& $request->has('type_connect')){
$seo = LarrockSeo::getModel()->whereSeoIdConnect($request->get('id_connect'))->whereSeoTypeConnect($request->get('type_connect'))->first();
if( !empty($request->get('seo_title')) || !empty($request->get('seo_description')) || !empty($request->get('seo_keywords'))){
if( !$seo){
$seo = LarrockSeo::getModel();
}
$seo->seo_id_connect = $request->get('id_connect');
$seo->seo_url_connect = $request->get('url_connect');
$seo->seo_title = $request->get('seo_title');
$seo->seo_description = $request->get('seo_description');
$seo->seo_keywords = $request->get('seo_keywords');
$seo->seo_type_connect = $request->get('type_connect');
if($seo->save()){
MessageLarrock::success('SEO обновлено');
}
}else{
if($seo){
$seo->delete($seo->id);
MessageLarrock::success('SEO удалено');
}
}
}
return TRUE;
}
/**
* Сохранение связей данных компонента (FormTagsLink)
* @param $request
* @return bool
*/
public function saveLinkData($request): bool
{
if( !$request->has('_jsvalidation') && $request->get('link')){
$modelParent = $request->get('modelParent');
$modelParentId = $request->get('modelParentId');
$modelChild = $request->get('modelChild');
$link = $request->get('link');
//Удаляем старые связи
$model = new Link();
$model->whereIdParent($modelParentId)->whereModelParent($modelParent)->whereModelChild($modelChild)->delete();
if($modelParent && $modelParentId && $modelChild && $link && \is_array($link) ){
foreach ($link as $value){
$model = new Link();
$model->id_parent = $request->get('modelParentId');
$model->model_parent = $request->get('modelParent');
$model->model_child = $request->get('modelChild');
$model->id_child = $value;
$model->save();
}
MessageLarrock::success('Связи обновлены');
}
}
return TRUE;
}
/**
* Подключение плагина загрузки фото
* @return $this
*/
public function addPluginImages()
{
$this->plugins_backend['images'] = 'images';
return $this;
}
/**
* Метод для добавления в модель новых пресетов картинок для Medialibrary
* @param array $conversions
*/
public function addCustomMediaConversions(array $conversions)
{
$this->customMediaConversions = $conversions;
}
/**
* Подключение плагина загрузки файлов
* @return $this
*/
public function addPluginFiles()
{
$this->plugins_backend['files'] = 'files';
return $this;
}
/**
* Плагин для генерации анонса новости для блока анонс новости
* @param int $categoryAnons ID категории с анонсами
* @return $this
*/
public function addAnonsToModule($categoryAnons)
{
$row = new FormCheckbox('anons_merge', 'Сгенерировать для анонса заголовок и ссылку на новость');
$this->rows['anons_merge'] = $rows_plugin[] = $row->setTab('anons', 'Создать анонс');
$row = new FormTextarea('anons_description', 'Текст для анонса новости в модуле');
$this->rows['anons_description'] = $rows_plugin[] = $row->setTab('anons', 'Создать анонс')->setTypo();
$this->settings['anons_category'] = $categoryAnons;
$this->plugins_backend['anons']['rows'] = $rows_plugin;
return $this;
}
/**
* Создание анонса новости
* @param $request
* @return bool
* @throws \Exception
*/
public function savePluginAnonsToModuleData($request)
{
if( !\Request::has('_jsvalidation') && (\Request::has('anons_merge') || !empty(\Request::get('anons_description')))){
if( !config('larrock.feed.anonsCategory')){
\Session::push('message.danger', 'larrock.feed.anonsCategory не задан. Анонс создан не будет');
return TRUE;
}
$anons = LarrockFeed::getModel();
$anons->title = \Request::get('title');
$anons->url = 'anons_'. \Request::get('id_connect') .''. random_int(1,9999);
$anons->category = LarrockFeed::getConfig()->settings['anons_category'];
$anons->user_id = \Auth::id();
$anons->active = 1;
$anons->position = LarrockFeed::getModel()->whereCategory(LarrockFeed::getConfig()->settings['anons_category'])->max('position') +1;
if(\Request::has('anons_merge')){
$original = LarrockFeed::getModel()->whereId(\Request::get('id_connect'))->first();
$anons->short = '<a href="'. $original->full_url .'">'. \Request::get('title') .'</a>';
}else{
$anons->short = \Request::get('anons_description');
}
if($anons->save()){
MessageLarrock::success('Анонс добавлен');
}else{
MessageLarrock::danger('Анонс не добавлен');
}
}
return TRUE;
}
/**
* Вспомогательный метод построения правил валидации из конфига полей компонента
* @param array|object $config
* @param string $action create|update
* @param null|string|integer $id
* @return array
*/
public static function _valid_construct($config, $action = 'create', $id = NULL)
{
$rules = array();
if(isset($config->rows)){
foreach($config->rows as $rows_value){
if( !empty($rows_value->valid)){
$rules[$rows_value->name] = $rows_value->valid;
if($action === 'update'){
$rules[$rows_value->name] = str_replace(':id', $id, $rules[$rows_value->name]);
}else{
$rules[$rows_value->name] = str_replace(',:id', '', $rules[$rows_value->name]);
}
}
}
}
return $rules;
}
/**
* Вывод данных полей компонента для табов
* @param Model $data
* @return $this
*/
public function tabbable($data)
{
if($this->plugins_backend){
$this->addDataPlugins($data);
}
$this->tabs = collect();
foreach($this->rows as $row_value){
$this->tabs->put(key($row_value->tab), current($row_value->tab));
}
foreach($this->tabs as $tab_key => $tab_value){
$render = '';
foreach($this->rows as $row_value){
$class_name = \get_class($row_value);
$load_class = new $class_name($row_value->name, $row_value->title);
if(key($row_value->tab) === $tab_key){
if(method_exists($load_class, 'render')){
$render .= $load_class->render($row_value, $data);
}else{
$this->tabs_data->put($tab_key, '<p>'. $class_name .' не определен для отрисовки</p>');
}
}
}
$this->tabs_data->put($tab_key, $render);
}
return $this;
}
/**
* Присоединяем данные от плагинов
* @param Model $data
*/
public function addDataPlugins($data)
{
if($this->plugins_backend && \is_array($this->plugins_backend)){
foreach ($this->plugins_backend as $key_plugin => $value_plugin){
if($key_plugin === 'seo' && $plugin_data = $data->getSeo){
foreach ($this->rows as $key => $value){
if($value->name === 'seo_title' || $value->name === 'seo_description' || $value->name === 'seo_keywords'){
$this->rows[$key]->default = $plugin_data->{$value->name};
}
}
}
}
}
}
/**
* Удаление данных плагинов
* @param $config
* @param Model $data Модель компонента с удаляемым материалом
*/
public function removeDataPlugins($config, $data)
{
if(\is_array($config->plugins_backend) && $config->plugins_backend){
foreach ($config->plugins_backend as $key_plugin => $value_plugin){
if($key_plugin === 'seo' && $seo = LarrockSeo::getModel()->whereSeoIdConnect(\Request::input('id_connect'))
->whereSeoTypeConnect(\Request::input('type_connect'))->first()){
$seo->delete();
}
}
}
$this->actionDetach($config, $data);
}
/**
* Метод изменяет данные прикрепляемых полей при изменении/удалении/добавлении материала
* ИСПОЛЬЗОВАНИЕ: в экшенах сохранения/удаления материалов после data->save()
*
* @param Component $config Предсгенерированный конфиг компонента
* @param Model $data Данные материала после сохранения ($data->save())
* @param Request|\Illuminate\Http\Request $request Параметры переданные в качестве запроса. Значение Request $request
*/
public function actionAttach($config, $data, Request $request)
{
foreach ($config->rows as $row){
if($row->attached){
foreach($data->getLink($row->modelChild)->get() as $link_item){
$data->getLink($row->modelChild)->detach($link_item);
}
if($request->has($row->name)){
$link_params = ['model_parent' => $row->modelParent, 'model_child' => $row->modelChild];
if(\is_array($request->get($row->name))){
foreach ($request->get($row->name) as $param){
if(isset($row->allowCreate) && $row->allowCreate && ( !$row->modelChild::find($param))){
if($find_param = $row->modelChild::whereTitle($param)->first()){
$param = $find_param->id;
}else{
$add_param = new $row->modelChild();
$add_param['title'] = $param;
$add_param->save();
$param = $add_param->id;
}
}
//Запись дополнительных данных в таблицу связей link из FormTags
if($row->costValue && $request->has('cost_'. $param)){
$link_params['cost'] = $request->get('cost_'. $param);
}
$data->getLink($row->modelChild)->attach($param, $link_params);
}
}else{
$data->getLink($row->modelChild)->attach($request->get($row->name), $link_params);
}
}
}
}
}
/**
* Удаление данных связей при удалении материала
* @param object $config Конфиг компонента
* @param Model $data Модель компонента с удаляемым материалом
*/
public function actionDetach($config, $data)
{
foreach($config->rows as $row){
if(isset($row->modelParent, $row->modelChild)){
//Получаем id прилинкованных данных
$getLink = $data->getLink($row->modelChild)->get();
//Удаляем связи
$data->getLink($row->modelChild)->detach($data->id);
//Удаляем поля в modelChild если у поля указана опция deleteIfNoLink и больше связей к этому материалу нет
if($row->deleteIfNoLink){
//Проверяем остались ли связи до modelChild от modelParent
foreach ($getLink as $link){
$linkModel = new Link();
if( !$linkModel->whereIdChild($link->id)->whereModelChild($row->modelChild)->first()){
$modelChild = new $row->modelChild();
$modelChild->whereId($link->id)->delete();
}
}
}
}
}
}
/**
* Перезапись конфига компонента (например внутри контроллера)
* @param $option
* @param $config
* @return $this
*/
public function overrideComponent($option, $config)
{
$this->{$option} = $config;
return $this;
}
/**
* Разрешить поиск по материалам компонента
* @return $this
*/
public function isSearchable()
{
$this->searchable = TRUE;
return $this;
}
/**
* Формирование пунктов меню компонента в админке
* @return string
*/
public function renderAdminMenu()
{
return '';
}
/**
* Метод встаивания данных компонента в карту сайта sitemap.xml
* @return null
*/
public function createSitemap()
{
return NULL;
}
/**
* Метод встаивания данных компонента в rss-feed
* @return null
*/
public function createRSS()
{
return NULL;
}
/**
* Данные для поиска по материалам компонента
* @param null|bool $admin Если TRUE - для поиска будут доступны вообще все элементы (не только опубликованные)
* @return null
*/
public function search($admin)
{
return NULL;
}
}