Completed
Push — master ( e47441...eaeba7 )
by Nekrasov
01:50
created

BaseRelationQuery   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 188
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 3

Importance

Changes 0
Metric Value
wmc 27
lcom 3
cbo 3
dl 0
loc 188
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A findFor() 0 4 2
A with() 0 19 6
B filterByModels() 0 32 8
A findWith() 0 14 3
B normalizeRelations() 0 33 7
A populateRelation() 0 10 1
1
<?php
2
3
4
namespace Arrilot\BitrixModels\Queries;
5
6
7
use Arrilot\BitrixModels\Helpers;
8
use Arrilot\BitrixModels\Models\BaseBitrixModel;
9
use Illuminate\Support\Collection;
10
11
/**
12
 * BaseRelationQuery содержит основные методы и свойства для загрузки релейшенов
13
 *
14
 * @method BaseBitrixModel first()
15
 * @method Collection|BaseBitrixModel[] getList()
16
 * @property array $select
17
 */
18
trait BaseRelationQuery
19
{
20
    /**
21
     * @var bool - когда запрос представляет связь с один-ко-многим. Если true, вернуться все найденные модели, иначе только первая
22
     */
23
    public $multiple;
24
    /**
25
     * @var string - настройка связи моделей. ключ_у_связанной_модели
26
     */
27
    public $foreignKey;
28
    /**
29
     * @var string - настройка связи моделей. ключ_у_текущей_модели
30
     */
31
    public $localKey;
32
    /**
33
     * @var BaseBitrixModel - модель, для которой производится загрузка релейшена
34
     */
35
    public $primaryModel;
36
    /**
37
     * @var array - список связей, которые должны быть подгружены при выполнении запроса
38
     */
39
    public $with;
40
41
    /**
42
     * Найти связанные записи для определенной модели [[$this->primaryModel]]
43
     * Этот метод вызывается когда релейшн вызывается ленивой загрузкой $model->relation
44
     * @return Collection|BaseBitrixModel[]|BaseBitrixModel - связанные модели
45
     * @throws \Exception
46
     */
47
    public function findFor()
48
    {
49
        return $this->multiple ? $this->getList() : $this->first();
50
    }
51
52
    /**
53
     * Определяет связи, которые должны быть загружены при выполнении запроса
54
     *
55
     * Передавая массив можно указать ключем - название релейшена, а значением - коллбек для кастомизации запроса
56
     *
57
     * @param array|string $with - связи, которые необходимо жадно подгрузить
58
     *  // Загрузить Customer и сразу для каждой модели подгрузить orders и country
59
     * Customer::query()->with(['orders', 'country'])->getList();
60
     *
61
     *  // Загрузить Customer и сразу для каждой модели подгрузить orders, а также для orders загрузить address
62
     * Customer::find()->with('orders.address')->getList();
63
     *
64
     *  // Загрузить Customer и сразу для каждой модели подгрузить country и orders (только активные)
65
     * Customer::find()->with([
66
     *     'orders' => function (BaseQuery $query) {
67
     *         $query->filter(['ACTIVE' => 'Y']);
68
     *     },
69
     *     'country',
70
     * ])->all();
71
     *
72
     * @return $this
73
     */
74
    public function with($with)
75
    {
76
        $with = is_string($with) ? func_get_args() : $with;
77
78
        if (empty($this->with)) {
79
            $this->with = $with;
80
        } elseif (!empty($with)) {
81
            foreach ($with as $name => $value) {
82
                if (is_int($name)) {
83
                    // дубликаты связей будут устранены в normalizeRelations()
84
                    $this->with[] = $value;
85
                } else {
86
                    $this->with[$name] = $value;
87
                }
88
            }
89
        }
90
91
        return $this;
92
    }
93
94
    /**
95
     * Добавить фильтр для загрзуки связи относительно моделей
96
     * @param Collection|BaseBitrixModel[] $models
97
     */
98
    protected function filterByModels($models)
99
    {
100
        $values = [];
101
        foreach ($models as $model) {
102
            if (($value = $model[$this->foreignKey]) !== null) {
103
                if (is_array($value)) {
104
                    $values = array_merge($values, $value);
105
                } else {
106
                    $values[] = $value;
107
                }
108
            }
109
        }
110
111
        $values = array_filter($values);
112
        if (empty($values)) {
113
            $this->stopQuery();
0 ignored issues
show
Bug introduced by
It seems like stopQuery() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
114
        }
115
116
        $primary = $this->localKey;
117
        if (preg_match('/^PROPERTY_(.*)_VALUE$/', $primary, $matches) && !empty($matches[1])) {
118
            $primary = 'PROPERTY_' . $matches[1];
119
        }
120
        $values = array_unique($values, SORT_REGULAR);
121
        if (count($values) == 1) {
122
            $values = current($values);
123
        } else {
124
            $this->prepareMultiFilter($primary, $values);
0 ignored issues
show
Bug introduced by
It seems like prepareMultiFilter() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
125
        }
126
127
        $this->filter([$primary => $values]);
0 ignored issues
show
Bug introduced by
The method filter() does not exist on Arrilot\BitrixModels\Queries\BaseRelationQuery. Did you maybe mean filterByModels()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
128
        $this->select[] = $primary;
129
    }
130
131
    /**
132
     * Подгрузить связанные модели для уже загруденных моделей
133
     * @param array $with - массив релейшенов, которые необходимо подгрузить
134
     * @param Collection|BaseBitrixModel[] $models модели, для которых загружать связи
135
     */
136
    public function findWith($with, &$models)
137
    {
138
        // --- получаем модель, на основании которой будем брать запросы релейшенов
139
        $primaryModel = $models->first();
0 ignored issues
show
Bug introduced by
It seems like $models is not always an object, but can also be of type array<integer,object<Arr...odels\BaseBitrixModel>>. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
140
        if (!$primaryModel instanceof BaseBitrixModel) {
141
            $primaryModel = $this->model;
0 ignored issues
show
Bug introduced by
The property model does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
142
        }
143
144
        $relations = $this->normalizeRelations($primaryModel, $with);
145
        /* @var $relation BaseQuery */
146
        foreach ($relations as $name => $relation) {
147
            $relation->populateRelation($name, $models);
0 ignored issues
show
Bug introduced by
It seems like $models defined by parameter $models on line 136 can also be of type object<Illuminate\Support\Collection>; however, Arrilot\BitrixModels\Que...ery::populateRelation() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
148
        }
149
    }
150
151
    /**
152
     * @param BaseBitrixModel $model - модель пустышка, чтобы получить запросы
153
     * @param array $with
154
     * @return BaseQuery[]
155
     */
156
    private function normalizeRelations($model, $with)
157
    {
158
        $relations = [];
159
        foreach ($with as $name => $callback) {
160
            if (is_int($name)) { // Если ключ - число, значит в значении написано название релейшена
161
                $name = $callback;
162
                $callback = null;
163
            }
164
165
            if (($pos = strpos($name, '.')) !== false) { // Если есть точка, значит указан вложенный релейшн
166
                $childName = substr($name, $pos + 1); // Название дочернего релейшена
167
                $name = substr($name, 0, $pos); // Название текущего релейшена
168
            } else {
169
                $childName = null;
170
            }
171
172
            if (!isset($relations[$name])) { // Указываем новый релейшн
173
                $relation = $model->getRelation($name); // Берем запрос
174
                $relation->primaryModel = null;
175
                $relations[$name] = $relation;
176
            } else {
177
                $relation = $relations[$name];
178
            }
179
180
            if (isset($childName)) {
181
                $relation->with[$childName] = $callback;
182
            } elseif ($callback !== null) {
183
                call_user_func($callback, $relation);
184
            }
185
        }
186
187
        return $relations;
188
    }
189
    /**
190
     * Находит связанные записи и заполняет их в первичных моделях.
191
     * @param string $name - имя релейшена
192
     * @param array $primaryModels - первичные модели
193
     * @return Collection|BaseBitrixModel[] - найденные модели
194
     */
195
    public function populateRelation($name, &$primaryModels)
196
    {
197
        $this->filterByModels($primaryModels);
198
199
        $models = $this->getList();
200
    
201
        Helpers::assocModels($primaryModels, $models, $this->foreignKey, $this->localKey, $name, $this->multiple);
202
203
        return $models;
204
    }
205
}
206