Completed
Push — master ( 80a943...142858 )
by Alexandr
01:44
created

ComponentPlugin::attachSeo()   D

Complexity

Conditions 10
Paths 6

Size

Total Lines 43
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 43
rs 4.8196
cc 10
eloc 34
nc 6
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
        /** @var Seo $seo */
41
        $seo = LarrockAdminSeo::getModel()->whereSeoIdConnect($event->model->id)->whereSeoTypeConnect($event->component->name)->first();
42
43
        if($seo){
44
            if( !empty($event->request->get('seo_title')) ||
45
                !empty($event->request->get('seo_description')) ||
46
                !empty($event->request->get('seo_seo_keywords'))){
47
                $seo->seo_id_connect = $event->model->id;
48
                $seo->seo_url_connect = $event->request->get('url_connect');
49
                $seo->seo_title = $event->request->get('seo_title');
50
                $seo->seo_description = $event->request->get('seo_description');
51
                $seo->seo_keywords = $event->request->get('seo_keywords');
52
                $seo->seo_type_connect = $event->component->name;
53
                if($seo->save()){
54
                    MessageLarrock::success('SEO обновлено');
55
                    return $seo;
56
                }
57
            }else{
58
                $seo->delete();
59
                MessageLarrock::success('SEO удалено');
60
                return $seo;
61
            }
62
        }else{
63
            if( !empty($event->request->get('seo_title')) ||
64
                !empty($event->request->get('seo_description')) ||
65
                !empty($event->request->get('seo_seo_keywords'))){
66
                $seo = LarrockAdminSeo::getModel();
67
                $seo->seo_id_connect = $event->request->get('id_connect');
68
                $seo->seo_url_connect = $event->request->get('url_connect');
69
                $seo->seo_title = $event->request->get('seo_title');
70
                $seo->seo_description = $event->request->get('seo_description');
71
                $seo->seo_keywords = $event->request->get('seo_keywords');
72
                $seo->seo_type_connect = $event->request->get('type_connect');
73
                if($seo->save()){
74
                    MessageLarrock::success('SEO добавлено');
75
                    return $seo;
76
                }
77
            }
78
        }
79
        return null;
80
    }
81
82
    /**
83
     * Создание анонса материала через модуль anonsCategory
84
     * @param $event
85
     * @return bool|Feed|null
86
     * @throws \Exception
87
     */
88
    protected function attachAnonsModule($event)
89
    {
90
        if( !$event->request->has('_jsvalidation') && ($event->request->has('anons_merge') || !empty($event->request->get('anons_description')))){
91
            if( !config('larrock.feed.anonsCategory')){
92
                MessageLarrock::danger('larrock.feed.anonsCategory не задан. Анонс создан не будет');
93
                return TRUE;
94
            }
95
            /** @var Feed $anons */
96
            $anons = LarrockFeed::getModel();
97
            $anons->title = $event->request->get('title');
98
            $anons->url = 'anons_'. $event->model->id .''. random_int(1,9999);
99
            $anons->category = LarrockFeed::getConfig()->settings['anons_category'];
100
            $anons->user_id = \Auth::id();
101
            $anons->active = 1;
102
            $anons->position = LarrockFeed::getModel()->whereCategory(LarrockFeed::getConfig()->settings['anons_category'])->max('position') +1;
103
104
            if($event->request->has('anons_merge')){
105
                $original = LarrockFeed::getModel()->whereId($event->request->get('id_connect'))->first();
106
                $anons->short = '<a href="'. $original->full_url .'">'. $event->request->get('title') .'</a>';
107
            }else{
108
                $anons->short = $event->request->get('anons_description');
109
            }
110
111
            if($anons->save()){
112
                MessageLarrock::success('Анонс добавлен');
113
                return $anons;
114
            }
115
            MessageLarrock::danger('Анонс не добавлен');
116
        }
117
        return null;
118
    }
119
120
    /**
121
     * Сохранение связей полей
122
     * @param $event
123
     */
124
    protected function attachRows($event)
125
    {
126
        if(\is_array($event->component->rows)) {
127
            foreach ($event->component->rows as $row) {
128
                if (isset($row->modelParent, $row->modelChild)) {
129
                    $add_params = ['model_parent' => $row->modelParent, 'model_child' => $row->modelChild];
130
131
                    if($event->request->has($row->name) && \is_array($event->request->get($row->name))){
132
                        foreach ($event->request->get($row->name) as $value){
133
                            $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...
134
                        }
135
                        if(isset($params)){
136
                            $event->model->getLink($row->modelChild)->sync($params);
137
                        }
138
                    }
139
                }
140
            }
141
        }
142
    }
143
144
    /**
145
     * Удаление всех связей материала компонента
146
     * @param $event
147
     */
148
    public function detach($event)
149
    {
150
        $this->detachRows($event);
151
        $this->detachPlugins($event);
152
    }
153
154
    /**
155
     * Удаление связей полей
156
     * @param $event
157
     */
158
    protected function detachRows($event)
159
    {
160
        if(\is_array($event->component->rows)){
161
            foreach ($event->component->rows as $row){
162
                if(isset($row->modelParent, $row->modelChild)){
163
                    //Получаем id прилинкованных данных
164
                    $getLink = $event->model->getLink($row->modelChild)->get();
165
166
                    //Удаляем связи
167
                    $event->model->linkQuery($row->modelChild)->delete();
168
169
                    //Удаляем поля в modelChild если у поля указана опция deleteIfNoLink и больше связей к этому материалу нет
170
                    if($row->deleteIfNoLink){
171
                        //Проверяем остались ли связи до modelChild от modelParent
172
                        foreach ($getLink as $link){
173
                            $linkModel = new Link();
174
                            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...
175
                                $modelChild = new $row->modelChild();
176
                                $modelChild->whereId($link->id)->delete();
177
                            }
178
                        }
179
                    }
180
                }
181
            }
182
        }
183
    }
184
185
    /**
186
     * Удаление данных плагинов
187
     * @param $event
188
     */
189
    protected function detachPlugins($event)
190
    {
191
        if(\is_array($event->component->plugins_backend)){
192
            foreach ($event->component->plugins_backend as $key_plugin => $value_plugin){
193
                //Detach SEO plugin
194
                if($key_plugin === 'seo' && $seo = LarrockAdminSeo::getModel()->whereSeoIdConnect($event->model->id)
195
                        ->whereSeoTypeConnect($event->component->name)->first()){
196
                    $seo->delete();
197
                }
198
            }
199
        }
200
    }
201
202
}