Completed
Push — master ( 9f3e69...d66716 )
by Nekrasov
01:38
created

addEventListenersForHelpersHighloadblockTables()   C

Complexity

Conditions 10
Paths 2

Size

Total Lines 48
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 48
rs 5.3454
cc 10
eloc 25
nc 2
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 Arrilot\BitrixModels;
4
5
use Arrilot\BitrixBlade\BladeProvider;
6
use Arrilot\BitrixModels\Debug\IlluminateQueryDebugger;
7
use Arrilot\BitrixModels\Models\EloquentModel;
8
use Bitrix\Main\Config\Configuration;
9
use DB;
10
use Illuminate\Container\Container;
11
use Illuminate\Events\Dispatcher;
12
use Illuminate\Pagination\Paginator;
13
use Illuminate\Database\Capsule\Manager as Capsule;
14
15
class ServiceProvider
16
{
17
    /**
18
     * Register the service provider.
19
     *
20
     * @return void
21
     */
22
    public static function register()
23
    {
24
        self::bootstrapIlluminatePagination();
25
    }
26
27
    /**
28
     * Register eloquent.
29
     *
30
     * @return void
31
     */
32
    public static function registerEloquent()
0 ignored issues
show
Coding Style introduced by
registerEloquent uses the super-global variable $_COOKIE which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
33
    {
34
        $capsule = self::bootstrapIlluminateDatabase();
35
        class_alias(Capsule::class, 'DB');
36
37
        if ($_COOKIE["show_sql_stat"] == "Y") {
38
            Capsule::enableQueryLog();
39
40
            $em = \Bitrix\Main\EventManager::getInstance();
41
            $em->addEventHandler('main', 'OnAfterEpilog', [IlluminateQueryDebugger::class, 'onAfterEpilogHandler']);
42
        }
43
44
        static::addEventListenersForHelpersHighloadblockTables($capsule);
0 ignored issues
show
Bug introduced by
Since addEventListenersForHelpersHighloadblockTables() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of addEventListenersForHelpersHighloadblockTables() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
45
    }
46
47
    /**
48
     * Bootstrap illuminate/pagination
49
     */
50
    protected static function bootstrapIlluminatePagination()
0 ignored issues
show
Coding Style introduced by
bootstrapIlluminatePagination uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
bootstrapIlluminatePagination uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
51
    {
52
        if (class_exists(BladeProvider::class)) {
53
            Paginator::viewFactoryResolver(function () {
54
                return BladeProvider::getViewFactory();
55
            });
56
        }
57
58
        Paginator::$defaultView = 'pagination.default';
59
        Paginator::$defaultSimpleView = 'pagination.simple-default';
60
61
        Paginator::currentPathResolver(function () {
62
            return $GLOBALS['APPLICATION']->getCurPage();
63
        });
64
65
        Paginator::currentPageResolver(function ($pageName = 'page') {
66
            $page = $_GET[$pageName];
67
68
            if (filter_var($page, FILTER_VALIDATE_INT) !== false && (int)$page >= 1) {
69
                return $page;
70
            }
71
72
            return 1;
73
        });
74
    }
75
76
    /**
77
     * Bootstrap illuminate/database
78
     * @return Capsule
79
     */
80
    protected static function bootstrapIlluminateDatabase()
81
    {
82
        $config = self::getBitrixDbConfig();
83
84
        $capsule = new Capsule(self::instantiateServiceContainer());
85
        $capsule->addConnection([
86
            'driver'    => 'mysql',
87
            'host'      => $config['host'],
88
            'database'  => $config['database'],
89
            'username'  => $config['login'],
90
            'password'  => $config['password'],
91
            'charset'   => 'utf8',
92
            'collation' => 'utf8_unicode_ci',
93
            'prefix'    => '',
94
            'strict'    => false,
95
        ]);
96
97
        if (class_exists(Dispatcher::class)) {
98
            $capsule->setEventDispatcher(new Dispatcher());
99
        }
100
101
        $capsule->setAsGlobal();
102
        $capsule->bootEloquent();
103
104
        return $capsule;
105
    }
106
107
    /**
108
     * Instantiate service container if it's not instantiated yet.
109
     */
110
    protected static function instantiateServiceContainer()
111
    {
112
        $container = Container::getInstance();
113
114
        if (!$container) {
115
            $container = new Container();
116
            Container::setInstance($container);
117
        }
118
119
        return $container;
120
    }
121
122
    /**
123
     * Get bitrix database configuration array.
124
     *
125
     * @return array
126
     */
127
    protected static function getBitrixDbConfig()
128
    {
129
        $config = Configuration::getInstance();
130
        $connections = $config->get('connections');
131
132
        return $connections['default'];
133
    }
134
135
    /**
136
     * Для множественных полей Highload блоков битрикс использует вспомогательные таблицы.
137
     * Данный метод вешает обработчики на eloquent события добавления и обновления записей которые будут актуализировать и эти таблицы.
138
     *
139
     * @param Capsule $capsule
140
     */
141
    private static function addEventListenersForHelpersHighloadblockTables(Capsule $capsule)
142
    {
143
        $dispatcher = $capsule->getEventDispatcher();
144
        if (!$dispatcher) {
145
            return;
146
        }
147
148
        $dispatcher->listen(['eloquent.created: *'], function($event, $payload) {
0 ignored issues
show
Unused Code introduced by
The parameter $event 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...
Unused Code introduced by
The parameter $payload 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...
149
            //                $model = $payload[0];
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
150
            //                dump(func_get_args());
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
151
        });
152
153
        $dispatcher->listen(['eloquent.updated: *', 'eloquent.created: *'], function($event, $payload) {
154
            /** @var EloquentModel $model */
155
            $model = $payload[0];
156
            if (empty($model->multipleHighloadBlockFields)) {
157
                return;
158
            }
159
160
            $dirty = $model->getDirty();
161
            foreach ($model->multipleHighloadBlockFields as $multipleHighloadBlockField) {
162
                if (isset($dirty[$multipleHighloadBlockField]) && !empty($model['ID'])) {
163
                    $tableName = $model->getTable().'_'.strtolower($multipleHighloadBlockField);
164
165
                    if (substr($event, 0, 16) === 'eloquent.updated') {
166
                        DB::table($tableName)->where('ID', $model['ID'])->delete();
167
                    }
168
169
                    $unserializedValues = unserialize($dirty[$multipleHighloadBlockField]);
170
                    if (!$unserializedValues) {
171
                        continue;
172
                    }
173
174
                    $newRows = [];
175
                    foreach ($unserializedValues as $unserializedValue) {
176
                        $newRows[] = [
177
                            'ID' => $model['ID'],
178
                            'VALUE' => $unserializedValue,
179
                        ];
180
                    }
181
182
                    if ($newRows) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $newRows 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...
183
                        DB::table($tableName)->insert($newRows);
184
                    }
185
                }
186
            }
187
        });
188
    }
189
}
190