Passed
Push — master ( ae9b6b...aec4ed )
by Wilmer
11:33 queued 09:14
created

ActiveQueryTrait::findWith()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 20
ccs 10
cts 10
cp 1
rs 9.9666
c 0
b 0
f 0
cc 4
nc 6
nop 2
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\ActiveRecord;
6
7
use Yiisoft\Db\Exception\InvalidConfigException;
8
9
/**
10
 * ActiveQueryTrait implements the common methods and properties for active record query classes.
11
 */
12
trait ActiveQueryTrait
13
{
14
    /**
15
     * @var string|null the name of the ActiveRecord class.
16
     */
17
    public ?string $modelClass;
18
19
    /**
20
     * @var array a list of relations that this query should be performed with
21
     */
22
    public array $with = [];
23
24
    /**
25
     * @var bool whether to return each record as an array. If false, an object of {@see modelClass} will be created to
26
     * represent each record.
27
     */
28
    public ?bool $asArray = null;
29
30
    /**
31
     * Sets the {@see asArray} property.
32
     *
33
     * @param bool $value whether to return the query results in terms of arrays instead of Active Records.
34
     *
35
     * @return $this the query object itself
36
     */
37 69
    public function asArray(?bool $value = true): self
38
    {
39 69
        $this->asArray = $value;
40
41 69
        return $this;
42
    }
43
44
    /**
45
     * Specifies the relations with which this query should be performed.
46
     *
47
     * The parameters to this method can be either one or multiple strings, or a single array of relation names and the
48
     * optional callbacks to customize the relations.
49
     *
50
     * A relation name can refer to a relation defined in {@see modelClass} or a sub-relation that stands for a relation
51
     * of a related record.
52
     *
53
     * For example, `orders.address` means the `address` relation defined
54
     * in the model class corresponding to the `orders` relation.
55
     *
56
     * The following are some usage examples:
57
     *
58
     * ```php
59
     * // find customers together with their orders and country
60
     * Customer::find()->with('orders', 'country')->all();
61
     * // find customers together with their orders and the orders' shipping address
62
     * Customer::find()->with('orders.address')->all();
63
     * // find customers together with their country and orders of status 1
64
     * Customer::find()->with([
65
     *     'orders' => function (ActiveQuery $query) {
66
     *         $query->andWhere('status = 1');
67
     *     },
68
     *     'country',
69
     * ])->all();
70
     * ```
71
     *
72
     * You can call `with()` multiple times. Each call will add relations to the existing ones.
73
     * For example, the following two statements are equivalent:
74
     *
75
     * ```php
76
     * Customer::find()->with('orders', 'country')->all();
77
     * Customer::find()->with('orders')->with('country')->all();
78
     * ```
79
     * @param array|string $with
80
     *
81
     * @return $this the query object itself
82
     */
83 72
    public function with(...$with): self
84
    {
85 72
        if (isset($with[0]) && \is_array($with[0])) {
86
            /* the parameter is given as an array */
87 42
            $with = $with[0];
88
        }
89
90 72
        if (empty($this->with)) {
91 72
            $this->with = $with;
92 6
        } elseif (!empty($with)) {
93 6
            foreach ($with as $name => $value) {
94 6
                if (\is_int($name)) {
95
                    /* repeating relation is fine as normalizeRelations() handle it well */
96 3
                    $this->with[] = $value;
97
                } else {
98 3
                    $this->with[$name] = $value;
99
                }
100
            }
101
        }
102
103 72
        return $this;
104
    }
105
106
    /**
107
     * Converts found rows into model instances.
108
     *
109
     * @param array $rows
110
     *
111
     * @return array|ActiveRecord[]
112
     */
113 147
    protected function createModels($rows): ?array
114
    {
115 147
        if ($this->asArray) {
116 33
            return $rows;
117
        } else {
118 147
            $models = [];
119
120
            /* @var $class ActiveRecord */
121 147
            $class = $this->modelClass;
122
123 147
            foreach ($rows as $row) {
124 147
                $model = $class::instantiate($row);
125 147
                $modelClass = \get_class($model);
126 147
                $modelClass::populateRecord($model, $row);
127
128 147
                $models[] = $model;
129
            }
130
131 147
            return $models;
132
        }
133
    }
134
135
    /**
136
     * Finds records corresponding to one or multiple relations and populates them into the primary models.
137
     *
138
     * @param array $with a list of relations that this query should be performed with. Please refer to {@see with()}
139
     * for details about specifying this parameter.
140
     * @param array|ActiveRecord[] $models the primary models (can be either AR instances or arrays)
141
     *
142
     * @throws InvalidConfigException
143
     *
144
     * @return void
145
     */
146 57
    public function findWith(array $with, array &$models): void
147
    {
148 57
        $primaryModel = \reset($models);
149
150 57
        if (!$primaryModel instanceof ActiveRecordInterface) {
151
            /* @var $modelClass ActiveRecordInterface */
152 9
            $modelClass = $this->modelClass;
153 9
            $primaryModel = $modelClass::instance();
0 ignored issues
show
Bug introduced by
The method instance() does not exist on Yiisoft\ActiveRecord\ActiveRecordInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Yiisoft\ActiveRecord\ActiveRecordInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

153
            /** @scrutinizer ignore-call */ 
154
            $primaryModel = $modelClass::instance();
Loading history...
154
        }
155
156 57
        $relations = $this->normalizeRelations($primaryModel, $with);
157
        /* @var $relation ActiveQuery */
158
159 57
        foreach ($relations as $name => $relation) {
160 57
            if ($relation->asArray === null) {
161
                // inherit asArray from primary query
162 57
                $relation->asArray($this->asArray);
163
            }
164
165 57
            $relation->populateRelation($name, $models);
166
        }
167 57
    }
168
169
    /**
170
     * @param ActiveRecord $model
171
     * @param array $with
172
     *
173
     * @return ActiveQueryInterface[]
174
     */
175 57
    private function normalizeRelations(ActiveRecord $model, array $with): array
176
    {
177 57
        $relations = [];
178
179 57
        foreach ($with as $name => $callback) {
180 57
            if (\is_int($name)) {
181 57
                $name = $callback;
182 57
                $callback = null;
183
            }
184
185 57
            if (($pos = \strpos($name, '.')) !== false) {
186
                // with sub-relations
187 9
                $childName = \substr($name, $pos + 1);
188 9
                $name = \substr($name, 0, $pos);
189
            } else {
190 57
                $childName = null;
191
            }
192
193 57
            if (!isset($relations[$name])) {
194 57
                $relation = $model->getRelation($name);
195 57
                $relation->primaryModel = null;
0 ignored issues
show
Bug introduced by
Accessing primaryModel on the interface Yiisoft\ActiveRecord\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
196 57
                $relations[$name] = $relation;
197
            } else {
198 6
                $relation = $relations[$name];
199
            }
200
201 57
            if (isset($childName)) {
202 9
                $relation->with[$childName] = $callback;
203 57
            } elseif ($callback !== null) {
204 18
                $callback($relation);
205
            }
206
        }
207
208 57
        return $relations;
209
    }
210
}
211