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

ComponentPlugin::attachAnonsModule()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 31
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 22
nc 6
nop 1
dl 0
loc 31
rs 6.7272
c 0
b 0
f 0
1
<?php
2
3
namespace Larrock\Core\Plugins;
4
5
use Larrock\ComponentFeed\Models\Feed;
6
use Larrock\Core\Models\Link;
7
use LarrockAdminSeo;
8
use LarrockFeed;
9
use Larrock\Core\Helpers\MessageLarrock;
10
use Larrock\Core\Models\Seo;
11
12
/**
13
 * Аттач/детач данных плагинов и связанных полей
14
 * Class ComponentPlugin
15
 * @package Larrock\Core\Plugins
16
 */
17
class ComponentPlugin
18
{
19
20
    /**
21
     * Сохранение связей полей и данных плагинов
22
     * @param $event
23
     * @throws \Exception
24
     */
25
    public function attach($event)
26
    {
27
        $this->attachRows($event);
28
        $this->attachSeo($event);
29
        $this->attachAnonsModule($event);
30
    }
31
32
    /**
33
     * Сохранение данных сео-плагина
34
     * @param $event
35
     * @throws \Exception
36
     * @return \Larrock\Core\Models\Seo|Seo|null
37
     */
38
    protected function attachSeo($event)
39
    {
40
        if( !$event->request->has('_jsvalidation')
41
            && ($event->request->has('seo_title') || $event->request->get('seo_description') || $event->request->get('seo_seo_keywords'))){
42
            /** @var Seo $seo */
43
            $seo = LarrockAdminSeo::getModel()->whereSeoIdConnect($event->model->id)->whereSeoTypeConnect($event->component->name)->first();
44
            if( !empty($event->request->get('seo_title')) || !empty($event->request->get('seo_description')) || !empty($event->request->get('seo_keywords'))){
45
                if( !$seo){
46
                    $seo = LarrockAdminSeo::getModel();
47
                }
48
                $seo->seo_id_connect = $event->request->get('id_connect');
49
                $seo->seo_url_connect = $event->request->get('url_connect');
50
                $seo->seo_title = $event->request->get('seo_title');
51
                $seo->seo_description = $event->request->get('seo_description');
52
                $seo->seo_keywords = $event->request->get('seo_keywords');
53
                $seo->seo_type_connect = $event->request->get('type_connect');
54
                if($seo->save()){
55
                    MessageLarrock::success('SEO обновлено');
56
                    return $seo;
57
                }
58
            }else{
59
                if($seo){
60
                    $seo->delete();
61
                    MessageLarrock::success('SEO удалено');
62
                    return $seo;
63
                }
64
            }
65
        }
66
        return null;
67
    }
68
69
    /**
70
     * Создание анонса материала через модуль anonsCategory
71
     * @param $event
72
     * @return bool|Feed|null
73
     * @throws \Exception
74
     */
75
    protected function attachAnonsModule($event)
76
    {
77
        if( !$event->request->has('_jsvalidation') && ($event->request->has('anons_merge') || !empty($event->request->get('anons_description')))){
78
            if( !config('larrock.feed.anonsCategory')){
79
                MessageLarrock::danger('larrock.feed.anonsCategory не задан. Анонс создан не будет');
80
                return TRUE;
81
            }
82
            /** @var Feed $anons */
83
            $anons = LarrockFeed::getModel();
84
            $anons->title = $event->request->get('title');
85
            $anons->url = 'anons_'. $event->model->id .''. random_int(1,9999);
86
            $anons->category = LarrockFeed::getConfig()->settings['anons_category'];
87
            $anons->user_id = \Auth::id();
88
            $anons->active = 1;
89
            $anons->position = LarrockFeed::getModel()->whereCategory(LarrockFeed::getConfig()->settings['anons_category'])->max('position') +1;
90
91
            if($event->request->has('anons_merge')){
92
                $original = LarrockFeed::getModel()->whereId($event->request->get('id_connect'))->first();
93
                $anons->short = '<a href="'. $original->full_url .'">'. $event->request->get('title') .'</a>';
94
            }else{
95
                $anons->short = $event->request->get('anons_description');
96
            }
97
98
            if($anons->save()){
99
                MessageLarrock::success('Анонс добавлен');
100
                return $anons;
101
            }
102
            MessageLarrock::danger('Анонс не добавлен');
103
        }
104
        return null;
105
    }
106
107
    /**
108
     * Сохранение связей полей
109
     * @param $event
110
     */
111
    protected function attachRows($event)
112
    {
113
        if(\is_array($event->component->rows)) {
114
            foreach ($event->component->rows as $row) {
115
                if (isset($row->modelParent, $row->modelChild)) {
116
                    $add_params = ['model_parent' => $row->modelParent, 'model_child' => $row->modelChild];
117
118
                    if($event->request->has($row->name) && \is_array($event->request->get($row->name))){
119
                        foreach ($event->request->get($row->name) as $value){
120
                            $params[$value] = $add_params;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = 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...
121
                        }
122
                        if(isset($params)){
123
                            $event->model->getLink($row->modelChild)->sync($params);
124
                        }
125
                    }
126
                }
127
            }
128
        }
129
    }
130
131
    /**
132
     * Удаление всех связей материала компонента
133
     * @param $event
134
     */
135
    public function detach($event)
136
    {
137
        $this->detachRows($event);
138
        $this->detachPlugins($event);
139
    }
140
141
    /**
142
     * Удаление связей полей
143
     * @param $event
144
     */
145
    protected function detachRows($event)
146
    {
147
        if(\is_array($event->component->rows)){
148
            foreach ($event->component->rows as $row){
149
                if(isset($row->modelParent, $row->modelChild)){
150
                    //Получаем id прилинкованных данных
151
                    $getLink = $event->model->getLink($row->modelChild)->get();
152
153
                    //Удаляем связи
154
                    $event->model->linkQuery($row->modelChild)->delete();
155
156
                    //Удаляем поля в modelChild если у поля указана опция deleteIfNoLink и больше связей к этому материалу нет
157
                    if($row->deleteIfNoLink){
158
                        //Проверяем остались ли связи до modelChild от modelParent
159
                        foreach ($getLink as $link){
160
                            $linkModel = new Link();
161
                            if( !$linkModel::whereIdChild($link->id)->whereModelChild($row->modelChild)->first()){
0 ignored issues
show
Bug introduced by
The method whereModelChild does only exist in Larrock\Core\Models\Link, but not in Illuminate\Database\Query\Builder.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
162
                                $modelChild = new $row->modelChild();
163
                                $modelChild->whereId($link->id)->delete();
164
                            }
165
                        }
166
                    }
167
                }
168
            }
169
        }
170
    }
171
172
    /**
173
     * Удаление данных плагинов
174
     * @param $event
175
     */
176
    protected function detachPlugins($event)
177
    {
178
        if(\is_array($event->component->plugins_backend)){
179
            foreach ($event->component->plugins_backend as $key_plugin => $value_plugin){
180
                //Detach SEO plugin
181
                if($key_plugin === 'seo' && $seo = LarrockAdminSeo::getModel()->whereSeoIdConnect($event->model->id)
182
                        ->whereSeoTypeConnect($event->component->name)->first()){
183
                    $seo->delete();
184
                }
185
            }
186
        }
187
    }
188
189
}