Completed
Push — master ( e3acb6...1d7e0e )
by Dmitry
03:19
created

ActiveQuery::joinWith()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
ccs 0
cts 4
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 2
1
<?php
2
3
/*
4
 * Tools to use API as ActiveRecord for Yii2
5
 *
6
 * @link      https://github.com/hiqdev/yii2-hiart
7
 * @package   yii2-hiart
8
 * @license   BSD-3-Clause
9
 * @copyright Copyright (c) 2015-2016, HiQDev (http://hiqdev.com/)
10
 */
11
12
namespace hiqdev\hiart;
13
14
use yii\base\NotSupportedException;
15
use yii\db\ActiveQueryInterface;
16
use yii\db\ActiveQueryTrait;
17
use yii\db\ActiveRelationTrait;
18
use yii\helpers\ArrayHelper;
19
20
class ActiveQuery extends Query implements ActiveQueryInterface
21
{
22
    use ActiveQueryTrait {
23
        createModels as defaultCreateModels;
24
    }
25
26
    use ActiveRelationTrait;
27
28
    /**
29
     * @event Event an event that is triggered when the query is initialized via [[init()]].
30
     */
31
    const EVENT_INIT = 'init';
32
33
    /**
34
     * @var array|null a list of relations that this query should be joined with
35
     */
36
    public $joinWith = [];
37
38
    /**
39
     * @var array options for search
40
     */
41
    public $options = [];
42
43
    /**
44
     * Constructor.
45
     *
46
     * @param string $modelClass the model class associated with this query
47
     * @param array $config configurations to be applied to the newly created query object
48
     */
49
    public function __construct($modelClass, $config = [])
50
    {
51
        $this->modelClass = $modelClass;
52
53
        parent::__construct($config);
54
    }
55
56
    /**
57
     * Initializes the object.
58
     * This method is called at the end of the constructor. The default implementation will trigger
59
     * an [[EVENT_INIT]] event. If you override this method, make sure you call the parent implementation at the end
60
     * to ensure triggering of the event.
61
     */
62
    public function init()
63
    {
64
        parent::init();
65
        $this->trigger(self::EVENT_INIT);
66
    }
67
68
    /**
69
     * Creates a DB command that can be used to execute this query.
70
     *
71
     * @param Connection $db the DB connection used to create the DB command.
72
     *                       If null, the DB connection returned by [[modelClass]] will be used.
73
     *
74
     * @return Command the created DB command instance.
75
     */
76
    public function createCommand($db = null)
77
    {
78
        if ($this->primaryModel !== null) {
79
            // lazy loading
80
            if (is_array($this->via)) {
81
                // via relation
82
                /* @var $viaQuery ActiveQuery */
83
                list($viaName, $viaQuery) = $this->via;
84
                if ($viaQuery->multiple) {
85
                    $viaModels = $viaQuery->all();
86
                    $this->primaryModel->populateRelation($viaName, $viaModels);
87
                } else {
88
                    $model = $viaQuery->one();
89
                    $this->primaryModel->populateRelation($viaName, $model);
90
                    $viaModels = $model === null ? [] : [$model];
91
                }
92
                $this->filterByModels($viaModels);
93
            } else {
94
                $this->filterByModels([$this->primaryModel]);
95
            }
96
        }
97
98
        /* @var $modelClass ActiveRecord */
99
        $modelClass = $this->modelClass;
100
        if ($db === null) {
101
            $db = $modelClass::getDb();
102
        }
103
104
        if ($this->type === null) {
105
            $this->type = $modelClass::type();
106
        }
107
        if ($this->index === null) {
108
            $this->index = $modelClass::index();
109
            $this->type = $modelClass::type();
110
        }
111
112
        $commandConfig = $db->getQueryBuilder()->build($this);
113
114
        return $db->createCommand($commandConfig);
115
    }
116
117
    /**
118
     * {@inheritdoc}
119
     */
120
    public function prepare()
121
    {
122
        // NOTE: because the same ActiveQuery may be used to build different SQL statements
123
        // (e.g. by ActiveDataProvider, one for count query, the other for row data query,
124
        // it is important to make sure the same ActiveQuery can be used to build SQL statements
125
        // multiple times.
126
        if (!empty($this->joinWith)) {
127
            $this->buildJoinWith();
128
            $this->joinWith = null;
129
        }
130
131
        return $this;
132
    }
133
134
    public function joinWith($with)
135
    {
136
        $this->joinWith[] = (array) $with;
137
138
        return $this;
139
    }
140
141
    private function buildJoinWith()
142
    {
143
        $join = $this->join;
144
        $this->join = [];
145
146
        $model = new $this->modelClass;
147
148
        foreach ($this->joinWith as $with) {
0 ignored issues
show
Bug introduced by
The expression $this->joinWith of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
149
            $this->joinWithRelations($model, $with);
150
151
            foreach ($with as $name => $callback) {
152
                if (is_int($name)) {
153
                    $this->join([$callback]);
154
                } else {
155
                    $this->join([$name => $callback]);
156
                }
157
158
                unset($with[$name]);
159
            }
160
        }
161
162
        if (!empty($join)) {
163
            // append explicit join to joinWith()
164
            // https://github.com/yiisoft/yii2/issues/2880
165
            $this->join = empty($this->join) ? $join : array_merge($this->join, $join);
166
        }
167
168
        if (empty($this->select) || true) {
169
            $this->addSelect(['*' => '*']);
170
            foreach ($this->joinWith as $join) {
0 ignored issues
show
Bug introduced by
The expression $this->joinWith of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
171
                $key = array_shift(array_keys($join));
0 ignored issues
show
Bug introduced by
array_keys($join) cannot be passed to array_shift() as the parameter $array expects a reference.
Loading history...
172
                $closure = array_shift($join);
173
174
                $this->addSelect(is_int($key) ? $closure : $key);
175
            }
176
        }
177
    }
178
179
    /**
180
     * @param ActiveRecord $model
181
     * @param $with
182
     */
183
    protected function joinWithRelations($model, $with)
184
    {
185
        foreach ($with as $name => $callback) {
186
            if (is_int($name)) {
187
                $name = $callback;
188
                $callback = null;
189
            }
190
191
            $primaryModel = $model;
192
            $parent = $this;
193
194
            if (!isset($relations[$name])) {
195
                $relations[$name] = $relation = $primaryModel->getRelation($name);
0 ignored issues
show
Bug introduced by
The variable $relations 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...
196
                if ($callback !== null) {
197
                    call_user_func($callback, $relation);
198
                }
199
                if (!empty($relation->joinWith)) {
0 ignored issues
show
Bug introduced by
Accessing joinWith on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
200
                    $relation->buildJoinWith();
201
                }
202
                $this->joinWithRelation($parent, $relation);
0 ignored issues
show
Compatibility introduced by
$relation of type object<yii\db\ActiveQueryInterface> is not a sub-type of object<hiqdev\hiart\ActiveQuery>. It seems like you assume a concrete implementation of the interface yii\db\ActiveQueryInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
203
            }
204
        }
205
    }
206
207
    /**
208
     * Joins a parent query with a child query.
209
     * The current query object will be modified accordingly.
210
     * @param ActiveQuery $parent
211
     * @param ActiveQuery $child
212
     */
213
    private function joinWithRelation($parent, $child)
0 ignored issues
show
Unused Code introduced by
The parameter $parent 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...
214
    {
215
        if (!empty($child->join)) {
216
            foreach ($child->join as $join) {
217
                $this->join[] = $join;
218
            }
219
        }
220
    }
221
222
    public function select($columns)
223
    {
224
        $this->select = $columns;
225
226
        return $this;
227
    }
228
229
    /**
230
     * @param array|string $columns
231
     * @return $this
232
     */
233
    public function addSelect($columns)
234
    {
235
        if (!is_array($columns)) {
236
            $columns = (array) $columns;
237
        }
238
239
        if ($this->select === null) {
240
            $this->select = $columns;
241
        } else {
242
            $this->select = array_merge($this->select, $columns);
243
        }
244
245
        return $this;
246
    }
247
248
    /**
249
     * Executes query and returns all results as an array.
250
     *
251
     * @param Connection $db the DB connection used to create the DB command.
252
     *                            If null, the DB connection returned by [[modelClass]] will be used.
253
     *
254
     * @return array the query results. If the query results in nothing, an empty array will be returned.
255
     */
256
    public function all($db = null)
257
    {
258
        if ($this->asArray) {
259
            // TODO implement with
260
            return parent::all($db);
0 ignored issues
show
Bug introduced by
It seems like $db defined by parameter $db on line 256 can also be of type object<hiqdev\hiart\Connection>; however, hiqdev\hiart\Query::all() does only seem to accept object<yii\db\Connection>|null, 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...
261
        }
262
263
        $rows = $this->createCommand($db)->search($this->options);
264
265
        return $this->populate($rows);
266
    }
267
268
    public function populate($rows)
269
    {
270
        if (empty($rows)) {
271
            return [];
272
        }
273
274
        $models = $this->createModels($rows);
275
        if (!empty($this->with)) {
276
            $this->findWith($this->with, $models);
277
        }
278
        foreach ($models as $model) {
279
            $model->afterFind();
280
        }
281
282
        return $models;
283
    }
284
285
    private function createModels($rows)
286
    {
287
        $models = [];
288
        if ($this->asArray) {
289
            if ($this->indexBy === null) {
290
                return $rows;
291
            }
292
            foreach ($rows as $row) {
293 View Code Duplication
                if (is_string($this->indexBy)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
294
                    $key = $row[$this->indexBy];
295
                } else {
296
                    $key = call_user_func($this->indexBy, $row);
297
                }
298
                $models[$key] = $row;
299
            }
300
        } else {
301
            /* @var $class ActiveRecord */
302
            $class = $this->modelClass;
303
            if ($this->indexBy === null) {
304
                foreach ($rows as $row) {
305
                    $model = $class::instantiate($row);
306
                    $modelClass = get_class($model);
307
                    $modelClass::populateRecord($model, $row);
308
                    $this->populateJoinedRelations($model, $row);
309
                    $models[] = $model;
310
                }
311
            } else {
312
                foreach ($rows as $row) {
313
                    $model = $class::instantiate($row);
314
                    $modelClass = get_class($model);
315
                    $modelClass::populateRecord($model, $row);
316
                    $this->populateJoinedRelations($model, $row);
317 View Code Duplication
                    if (is_string($this->indexBy)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
318
                        $key = $model->{$this->indexBy};
319
                    } else {
320
                        $key = call_user_func($this->indexBy, $model);
321
                    }
322
                    $models[$key] = $model;
323
                }
324
            }
325
        }
326
327
        return $models;
328
    }
329
330
    /**
331
     * Populates joined relations from [[join]] array.
332
     *
333
     * @param ActiveRecord $model
334
     * @param array $row
335
     */
336
    public function populateJoinedRelations($model, array $row)
337
    {
338
        foreach ($row as $key => $value) {
339
            if (empty($this->join) || !is_array($value) || $model->hasAttribute($key)) {
340
                continue;
341
            }
342
            foreach ($this->join as $join) {
343
                $name = array_shift(array_keys($join));
0 ignored issues
show
Bug introduced by
array_keys($join) cannot be passed to array_shift() as the parameter $array expects a reference.
Loading history...
344
                $closure = array_shift($join);
345
346
                if (is_int($name)) {
347
                    $name = $closure;
348
                    $closure = null;
349
                }
350
                if ($name !== $key) {
351
                    continue;
352
                }
353
                if ($model->isRelationPopulated($name)) {
354
                    continue 2;
355
                }
356
                $records = [];
357
                $relation = $model->getRelation($name);
358
                $relationClass = $relation->modelClass;
0 ignored issues
show
Bug introduced by
Accessing modelClass on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
359
                if ($closure !== null) {
360
                    call_user_func($closure, $relation);
361
                }
362
                $relation->prepare();
363
364
                if ($relation->multiple) {
0 ignored issues
show
Bug introduced by
Accessing multiple on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
365
                    foreach ($value as $item) {
366
                        $relationModel = $relationClass::instantiate($item);
367
                        $relationModelClass = get_class($relationModel);
368
                        $relationModelClass::populateRecord($relationModel, $item);
369
                        $relation->populateJoinedRelations($relationModel, $item);
370
                        if ($relation->indexBy !== null) {
0 ignored issues
show
Bug introduced by
Accessing indexBy on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
371
                            $index = is_string($relation->indexBy)
0 ignored issues
show
Bug introduced by
Accessing indexBy on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
372
                                ? $relationModel[$relation->indexBy]
0 ignored issues
show
Bug introduced by
Accessing indexBy on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
373
                                : call_user_func($relation->indexBy, $relationModel);
0 ignored issues
show
Bug introduced by
Accessing indexBy on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
374
                            $records[$index] = $relationModel;
375
                        } else {
376
                            $records[] = $relationModel;
377
                        }
378
                    }
379
                } else {
380
                    $relationModel = $relationClass::instantiate($value);
381
                    $relationModelClass = get_class($relationModel);
382
                    $relationModelClass::populateRecord($relationModel, $value);
383
                    $relation->populateJoinedRelations($relationModel, $value);
384
                    $records = $relationModel;
385
                }
386
387
                $model->populateRelation($name, $records);
388
            }
389
        }
390
    }
391
392
    /**
393
     * Executes query and returns a single row of result.
394
     *
395
     * @param Connection $db the DB connection used to create the DB command.
396
     *                       If null, the DB connection returned by [[modelClass]] will be used.
397
     *
398
     * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
399
     *                                 the query result may be either an array or an ActiveRecord object. Null will be returned
400
     *                                 if the query results in nothing.
401
     */
402
    public function one($db = null)
403
    {
404
        //        $result = $this->createCommand($db)->get();
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...
405
406
        $result = $this->createCommand($db)->search(ArrayHelper::merge(['limit' => 1], $this->options));
407
        if (empty($result)) {
408
            return null;
409
        }
410
        $result = reset($result);
411
412
        if ($this->asArray) {
413
            // TODO implement with()
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% 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...
414
//            /* @var $modelClass ActiveRecord */
415
//            $modelClass = $this->modelClass;
416
//            $model = $result['_source'];
417
//            $pk = $modelClass::primaryKey()[0];
418
//            if ($pk === '_id') {
419
//                $model['_id'] = $result['_id'];
420
//            }
421
//            $model['_score'] = $result['_score'];
422
//            if (!empty($this->with)) {
423
//                $models = [$model];
424
//                $this->findWith($this->with, $models);
425
//                $model = $models[0];
426
//            }
427
            return $result;
428
        }
429
430
        /* @var $class ActiveRecord */
431
        $class = $this->modelClass;
432
        $model = $class::instantiate($result);
433
        $class::populateRecord($model, $result);
434
        $this->populateJoinedRelations($model, $result);
435
        if (!empty($this->with)) {
436
            $models = [$model];
437
            $this->findWith($this->with, $models);
438
            $model = $models[0];
439
        }
440
        $model->afterFind();
441
442
        return $model;
443
    }
444
445
    /**
446
     * {@inheritdoc}
447
     */
448
    public function search($db = null, $options = [])
449
    {
450
        $result = $this->createCommand($db)->search($options);
451
        // TODO implement with() for asArray
452
        if (!empty($result) && !$this->asArray) {
453
            $models = $this->createModels($result);
454
            if (!empty($this->with)) {
455
                $this->findWith($this->with, $models);
456
            }
457
            foreach ($models as $model) {
458
                $model->afterFind();
459
            }
460
            $result = $models;
461
        }
462
463
        return $result;
464
    }
465
466
    /**
467
     * {@inheritdoc}
468
     */
469
    public function column($field, $db = null)
470
    {
471
        if ($field === '_id') {
472
            $command = $this->createCommand($db);
473
            $command->queryParts['fields'] = [];
474
            $command->queryParts['_source'] = false;
475
            $result = $command->search();
476
            if (empty($result['hits']['hits'])) {
477
                return [];
478
            }
479
            $column = [];
480
            foreach ($result['hits']['hits'] as $row) {
481
                $column[] = $row['_id'];
482
            }
483
484
            return $column;
485
        }
486
487
        return parent::column($field, $db);
488
    }
489
}
490