Completed
Pull Request — master (#26)
by
unknown
06:22
created

BaseRelationQuery   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 188
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 2

Importance

Changes 0
Metric Value
wmc 27
lcom 3
cbo 2
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\Models\BaseBitrixModel;
8
use Illuminate\Support\Collection;
9
10
/**
11
 * BaseRelationQuery содержит основные методы и свойства для загрузки релейшенов
12
 *
13
 * @method BaseBitrixModel first()
14
 * @method Collection|BaseBitrixModel[] getList()
15
 * @property array $select
16
 */
17
trait BaseRelationQuery
18
{
19
    /**
20
     * @var bool - когда запрос представляет связь с один-ко-многим. Если true, вернуться все найденные модели, иначе только первая
21
     */
22
    public $multiple;
23
    /**
24
     * @var string - настройка связи моделей. ключ_у_связанной_модели
25
     */
26
    public $foreignKey;
27
    /**
28
     * @var string - настройка связи моделей. ключ_у_текущей_модели
29
     */
30
    public $localKey;
31
    /**
32
     * @var BaseBitrixModel - модель, для которой производится загрузка релейшена
33
     */
34
    public $primaryModel;
35
    /**
36
     * @var array - список связей, которые должны быть подгружены при выполнении запроса
37
     */
38
    public $with;
39
40
    /**
41
     * Найти связанные записи для определенной модели [[$this->primaryModel]]
42
     * Этот метод вызывается когда релейшн вызывается ленивой загрузкой $model->relation
43
     * @return Collection|BaseBitrixModel[]|BaseBitrixModel - связанные модели
44
     * @throws \Exception
45
     */
46
    public function findFor()
47
    {
48
        return $this->multiple ? $this->getList() : $this->first();
49
    }
50
51
    /**
52
     * Определяет связи, которые должны быть загружены при выполнении запроса
53
     *
54
     * Передавая массив можно указать ключем - название релейшена, а значением - коллбек для кастомизации запроса
55
     *
56
     * @param array|string $with - связи, которые необходимо жадно подгрузить
57
     *  // Загрузить Customer и сразу для каждой модели подгрузить orders и country
58
     * Customer::query()->with(['orders', 'country'])->getList();
59
     *
60
     *  // Загрузить Customer и сразу для каждой модели подгрузить orders, а также для orders загрузить address
61
     * Customer::find()->with('orders.address')->getList();
62
     *
63
     *  // Загрузить Customer и сразу для каждой модели подгрузить country и orders (только активные)
64
     * Customer::find()->with([
65
     *     'orders' => function (BaseQuery $query) {
66
     *         $query->filter(['ACTIVE' => 'Y']);
67
     *     },
68
     *     'country',
69
     * ])->all();
70
     *
71
     * @return $this
72
     */
73
    public function with($with)
74
    {
75
        $with = is_string($with) ? func_get_args() : $with;
76
77
        if (empty($this->with)) {
78
            $this->with = $with;
79
        } elseif (!empty($with)) {
80
            foreach ($with as $name => $value) {
81
                if (is_int($name)) {
82
                    // дубликаты связей будут устранены в normalizeRelations()
83
                    $this->with[] = $value;
84
                } else {
85
                    $this->with[$name] = $value;
86
                }
87
            }
88
        }
89
90
        return $this;
91
    }
92
93
    /**
94
     * Добавить фильтр для загрзуки связи относительно моделей
95
     * @param Collection|BaseBitrixModel[] $models
96
     */
97
    protected function filterByModels($models)
98
    {
99
        $values = [];
100
        foreach ($models as $model) {
101
            if (($value = $model[$this->foreignKey]) !== null) {
102
                if (is_array($value)) {
103
                    $values = array_merge($values, $value);
104
                } else {
105
                    $values[] = $value;
106
                }
107
            }
108
        }
109
110
        $values = array_filter($values);
111
        if (empty($values)) {
112
            $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...
113
        }
114
115
        $primary = $this->localKey;
116
        if (preg_match('/^PROPERTY_(.*)_VALUE$/', $primary, $matches) && !empty($matches[1])) {
117
            $primary = 'PROPERTY_' . $matches[1];
118
        }
119
        $values = array_unique($values, SORT_REGULAR);
120
        if (count($values) == 1) {
121
            $values = current($values);
122
        } else {
123
            $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...
124
        }
125
126
        $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...
127
        $this->select[] = $primary;
128
    }
129
130
    /**
131
     * Подгрузить связанные модели для уже загруденных моделей
132
     * @param array $with - массив релейшенов, которые необходимо подгрузить
133
     * @param Collection|BaseBitrixModel[] $models модели, для которых загружать связи
134
     */
135
    public function findWith($with, &$models)
136
    {
137
        // --- получаем модель, на основании которой будем брать запросы релейшенов
138
        $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...
139
        if (!$primaryModel instanceof BaseBitrixModel) {
140
            $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...
141
        }
142
143
        $relations = $this->normalizeRelations($primaryModel, $with);
144
        /* @var $relation BaseQuery */
145
        foreach ($relations as $name => $relation) {
146
            $relation->populateRelation($name, $models);
0 ignored issues
show
Bug introduced by
It seems like $models defined by parameter $models on line 135 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...
147
        }
148
    }
149
150
    /**
151
     * @param BaseBitrixModel $model - модель пустышка, чтобы получить запросы
152
     * @param array $with
153
     * @return BaseQuery[]
154
     */
155
    private function normalizeRelations($model, $with)
156
    {
157
        $relations = [];
158
        foreach ($with as $name => $callback) {
159
            if (is_int($name)) { // Если ключ - число, значит в значении написано название релейшена
160
                $name = $callback;
161
                $callback = null;
162
            }
163
164
            if (($pos = strpos($name, '.')) !== false) { // Если есть точка, значит указан вложенный релейшн
165
                $childName = substr($name, $pos + 1); // Название дочернего релейшена
166
                $name = substr($name, 0, $pos); // Название текущего релейшена
167
            } else {
168
                $childName = null;
169
            }
170
171
            if (!isset($relations[$name])) { // Указываем новый релейшн
172
                $relation = $model->getRelation($name); // Берем запрос
173
                $relation->primaryModel = null;
174
                $relations[$name] = $relation;
175
            } else {
176
                $relation = $relations[$name];
177
            }
178
179
            if (isset($childName)) {
180
                $relation->with[$childName] = $callback;
181
            } elseif ($callback !== null) {
182
                call_user_func($callback, $relation);
183
            }
184
        }
185
186
        return $relations;
187
    }
188
    /**
189
     * Находит связанные записи и заполняет их в первичных моделях.
190
     * @param string $name - имя релейшена
191
     * @param array $primaryModels - первичные модели
192
     * @return Collection|BaseBitrixModel[] - найденные модели
193
     */
194
    public function populateRelation($name, &$primaryModels)
195
    {
196
        $this->filterByModels($primaryModels);
197
198
        $models = $this->getList();
199
        
200
        Helpers::assocModels($primaryModels, $models, $this->foreignKey, $this->localKey, $name, $this->multiple);
201
202
        return $models;
203
    }
204
}
205