Completed
Push — master ( 80cf44...323ba1 )
by Alexandr
11s
created

ComponentPlugin::attachSeo()   C

Complexity

Conditions 10
Paths 6

Size

Total Lines 47
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 47
rs 5.1578
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 LarrockFeed;
6
use LarrockAdminSeo;
7
use Larrock\Core\Models\Seo;
8
use Larrock\Core\Models\Link;
9
use Larrock\ComponentFeed\Models\Feed;
10
use Larrock\Core\Helpers\MessageLarrock;
11
12
/**
13
 * Аттач/детач данных плагинов и связанных полей
14
 * Class ComponentPlugin.
15
 */
16
class ComponentPlugin
17
{
18
    /**
19
     * Сохранение связей полей и данных плагинов.
20
     * @param $event
21
     * @throws \Exception
22
     */
23
    public function attach($event)
24
    {
25
        $this->attachRows($event);
26
        $this->attachSeo($event);
27
        $this->attachAnonsModule($event);
28
    }
29
30
    /**
31
     * Сохранение данных сео-плагина.
32
     * @param $event
33
     * @throws \Exception
34
     * @return \Larrock\Core\Models\Seo|Seo|null
35
     */
36
    protected function attachSeo($event)
37
    {
38
        /** @var Seo $seo */
39
        $seo = LarrockAdminSeo::getModel()->whereSeoIdConnect($event->model->id)->whereSeoTypeConnect($event->component->name)->first();
40
41
        if ($seo) {
42
            if (! empty($event->request->get('seo_title')) ||
43
                ! empty($event->request->get('seo_description')) ||
44
                ! empty($event->request->get('seo_seo_keywords'))) {
45
                $seo->seo_id_connect = $event->model->id;
46
                $seo->seo_url_connect = $event->request->get('url_connect');
47
                $seo->seo_title = $event->request->get('seo_title');
48
                $seo->seo_description = $event->request->get('seo_description');
49
                $seo->seo_keywords = $event->request->get('seo_keywords');
50
                $seo->seo_type_connect = $event->component->name;
51
                if ($seo->save()) {
52
                    MessageLarrock::success('SEO обновлено');
53
54
                    return $seo;
55
                }
56
            } else {
57
                $seo->delete();
58
                MessageLarrock::success('SEO удалено');
59
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
76
                    return $seo;
77
                }
78
            }
79
        }
80
81
        return null;
82
    }
83
84
    /**
85
     * Создание анонса материала через модуль anonsCategory.
86
     * @param $event
87
     * @return bool|Feed|null
88
     * @throws \Exception
89
     */
90
    protected function attachAnonsModule($event)
91
    {
92
        if (! $event->request->has('_jsvalidation') && ($event->request->has('anons_merge') || ! empty($event->request->get('anons_description')))) {
93
            if (! config('larrock.feed.anonsCategory')) {
94
                MessageLarrock::danger('larrock.feed.anonsCategory не задан. Анонс создан не будет');
95
96
                return true;
97
            }
98
            /** @var Feed $anons */
99
            $anons = LarrockFeed::getModel();
100
            $anons->title = $event->request->get('title');
101
            $anons->url = 'anons_'.$event->model->id.''.random_int(1, 9999);
102
            $anons->category = LarrockFeed::getConfig()->settings['anons_category'];
103
            $anons->user_id = \Auth::id();
104
            $anons->active = 1;
105
            $anons->position = LarrockFeed::getModel()->whereCategory(LarrockFeed::getConfig()->settings['anons_category'])->max('position') + 1;
106
107
            if ($event->request->has('anons_merge')) {
108
                $original = LarrockFeed::getModel()->whereId($event->request->get('id_connect'))->first();
109
                $anons->short = '<a href="'.$original->full_url.'">'.$event->request->get('title').'</a>';
110
            } else {
111
                $anons->short = $event->request->get('anons_description');
112
            }
113
114
            if ($anons->save()) {
115
                MessageLarrock::success('Анонс добавлен');
116
117
                return $anons;
118
            }
119
            MessageLarrock::danger('Анонс не добавлен');
120
        }
121
122
        return null;
123
    }
124
125
    /**
126
     * Сохранение связей полей.
127
     * @param $event
128
     */
129
    protected function attachRows($event)
130
    {
131
        if (\is_array($event->component->rows)) {
132
            foreach ($event->component->rows as $row) {
133
                if (isset($row->modelParent, $row->modelChild)) {
134
                    $add_params = ['model_parent' => $row->modelParent, 'model_child' => $row->modelChild];
135
136
                    if ($event->request->has($row->name)) {
137
                        if (\is_array($event->request->get($row->name))) {
138
                            foreach ($event->request->get($row->name) as $value) {
139
                                $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...
140
                            }
141
                            if (isset($params)) {
142
                                $event->model->getLink($row->modelChild)->sync($params);
143
                            }
144
                        } elseif (! \is_object($event->request->get($row->name))) {
145
                            $params[$event->request->get($row->name)] = $add_params;
0 ignored issues
show
Bug introduced by
The variable $params does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
146
                            $event->model->getLink($row->modelChild)->sync($params);
147
                        }
148
                    }
149
                }
150
            }
151
        }
152
    }
153
154
    /**
155
     * Удаление всех связей материала компонента.
156
     * @param $event
157
     */
158
    public function detach($event)
159
    {
160
        $this->detachRows($event);
161
        $this->detachPlugins($event);
162
    }
163
164
    /**
165
     * Удаление связей полей.
166
     * @param $event
167
     */
168
    protected function detachRows($event)
169
    {
170
        if (\is_array($event->component->rows)) {
171
            foreach ($event->component->rows as $row) {
172
                if (isset($row->modelParent, $row->modelChild)) {
173
                    //Получаем id прилинкованных данных
174
                    $getLink = $event->model->getLink($row->modelChild)->get();
175
176
                    //Удаляем связи
177
                    $event->model->linkQuery($row->modelChild)->delete();
178
179
                    //Удаляем поля в modelChild если у поля указана опция setDeleteIfNoLink и больше связей к этому материалу нет
180
                    if ($row->deleteIfNoLink) {
181
                        //Проверяем остались ли связи до modelChild от modelParent
182
                        foreach ($getLink as $link) {
183
                            $linkModel = new Link();
184
                            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...
185
                                $modelChild = new $row->modelChild();
186
                                $modelChild->whereId($link->id)->delete();
187
                            }
188
                        }
189
                    }
190
                }
191
            }
192
        }
193
    }
194
195
    /**
196
     * Удаление данных плагинов.
197
     * @param $event
198
     */
199
    protected function detachPlugins($event)
200
    {
201
        if (\is_array($event->component->plugins_backend)) {
202
            foreach ($event->component->plugins_backend as $key_plugin => $value_plugin) {
203
                //Detach SEO plugin
204
                if ($key_plugin === 'seo' && $seo = LarrockAdminSeo::getModel()->whereSeoIdConnect($event->model->id)
205
                        ->whereSeoTypeConnect($event->component->name)->first()) {
206
                    $seo->delete();
207
                }
208
            }
209
        }
210
    }
211
}
212