Passed
Push — master ( 89d796...1246a9 )
by Vitaly
29s
created

Entity::select()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 14
rs 9.2
cc 4
eloc 6
nc 3
nop 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: VITALYIEGOROV
5
 * Date: 11.12.15
6
 * Time: 17:35
7
 */
8
namespace samsoncms\api\query;
9
10
use samson\activerecord\dbQuery;
11
use samsonframework\orm\Argument;
12
use samsonframework\orm\ArgumentInterface;
13
use samsoncms\api\CMS;
14
use samsoncms\api\exception\EntityFieldNotFound;
15
use samsoncms\api\Field;
16
use samsoncms\api\Material;
17
use samsonframework\orm\Condition;
18
use samsonframework\orm\ConditionInterface;
19
use samsonframework\orm\QueryInterface;
20
21
/**
22
 * Generic SamsonCMS Entity query.
23
 * @package samsoncms\api\query
24
 */
25
class Entity extends Generic
26
{
27
    /** @var array Collection of all additional fields names */
28
    public static $fieldNames = array();
29
30
    /** @var array Collection of localized additional fields identifiers */
31
    protected static $localizedFieldIDs = array();
32
33
    /** @var array Collection of NOT localized additional fields identifiers */
34
    protected static $notLocalizedFieldIDs = array();
35
36
    /** @var array Collection of all additional fields identifiers */
37
    protected static $fieldIDs = array();
38
39
    /** @var  @var array Collection of additional fields value column names */
40
    protected static $fieldValueColumns = array();
41
42
    /** @var Condition Collection of entity field filter */
43
    protected $fieldFilter = array();
44
45
    /** @var string Query locale */
46
    protected $locale = '';
47
48
    /** @var array Collection of additional fields for ordering */
49
    protected $entityOrderBy = array();
50
51
    /** @var array Collection of search fields for query */
52
    protected $searchFilter = array();
53
54
    /**
55
     * Select specified entity fields.
56
     * If this method is called then only selected entity fields
57
     * would be return in entity instances.
58
     *
59
     * @param mixed $fieldNames Entity field name or collection of names
60
     * @return $this Chaining
61
     */
62
    public function select($fieldNames)
63
    {
64
        // Convert argument to array and iterate
65
        foreach ((!is_array($fieldNames) ? array($fieldNames) : $fieldNames) as $fieldName) {
66
            // Try to find entity additional field
67
            $pointer = &static::$fieldNames[$fieldName];
68
            if (null !== $pointer) {
69
                // Store selected additional field buy FieldID and Field name
70
                $this->selectedFields[$pointer] = $fieldName;
71
            }
72
        }
73
74
        return $this;
75
    }
76
77
    /**
78
     * Set additional field for sorting.
79
     *
80
     * @param string $fieldName Additional field name
81
     * @param string $order Sorting order
82
     * @return $this Chaining
83
     */
84
    public function orderBy($fieldName, $order = 'ASC')
85
    {
86
        if (array_key_exists($fieldName, static::$fieldNames)) {
87
            $this->entityOrderBy = array($fieldName, $order);
88
        } else {
89
            parent::orderBy($fieldName, $order);
90
        }
91
92
        return $this;
93
    }
94
95
    /**
96
     * Search entity fields by text.
97
     *
98
     * @param string $text Searching text
99
     * @return $this
100
     */
101
    public function search($text)
102
    {
103
        $this->searchFilter[] = $text;
104
105
        return $this;
106
    }
107
108
    /**
109
     * Set resulting query limits.
110
     *
111
     * @param integer $offset Starting index
112
     * @param integer|null $count Entities count
113
     * @return $this Chaining
114
     */
115
    public function limit($offset, $count = null)
116
    {
117
        $this->limit = array($offset, $count);
118
119
        return $this;
120
    }
121
122
    /**
123
     * Add condition to current query.
124
     *
125
     * @param string $fieldName Entity field name
126
     * @param string $fieldValue Value
127
     * @param string $fieldRelation Entity field to value relation
128
     * @return $this Chaining
129
     */
130
    public function where($fieldName, $fieldValue = null, $fieldRelation = ArgumentInterface::EQUAL)
131
    {
132
        // Try to find entity additional field
133
        $pointer = &static::$fieldNames[$fieldName];
134
        if (isset($pointer)) {
135
            // Store additional field filter value
136
            $this->fieldFilter[$pointer] = (new Condition())->add(static::$fieldValueColumns[$pointer], $fieldValue, $fieldRelation);
137
        } else {
138
            parent::where($fieldName, $fieldValue, $fieldRelation);
139
        }
140
141
        return $this;
142
    }
143
144
    /** @return array Collection of entity identifiers */
145
    protected function findEntityIDs()
146
    {
147
        $entityIDs = array();
148
        if ($this->conditions) {
149
            $entityIDs = $this->query
150
                ->entity(Material::ENTITY)
151
                ->whereCondition($this->conditions)
152
                ->fields(Material::F_PRIMARY);
153
        }
154
155
        // TODO: Find and describe approach with maximum generic performance
156
        $entityIDs = $this->findByAdditionalFields(
157
            $this->fieldFilter,
0 ignored issues
show
Documentation introduced by
$this->fieldFilter is of type object<samsonframework\orm\Condition>, but the function expects a array<integer,object<sam...amework\orm\Condition>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
158
            $this->findByNavigationIDs($entityIDs)
159
        );
160
161
        // Perform sorting if necessary
162 View Code Duplication
        if (count($this->entityOrderBy) === 2) {
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...
163
            $entityIDs = $this->applySorting($entityIDs, $this->entityOrderBy[0], $this->entityOrderBy[1]);
164
        }
165
166
        // Perform sorting in parent fields if necessary
167 View Code Duplication
        if (count($this->orderBy) === 2) {
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...
168
            $entityIDs = $this->applySorting($entityIDs, $this->orderBy[0], $this->orderBy[1]);
169
        }
170
171
        // Perform limits if necessary
172
        if (count($this->limit)) {
173
            $entityIDs = array_slice($entityIDs, $this->limit[0], $this->limit[1]);
174
        }
175
176
        return $entityIDs;
177
    }
178
179
    /**
180
     * Get collection of entity identifiers filtered by navigation identifiers.
181
     *
182
     * @param array $entityIDs Additional collection of entity identifiers for filtering
183
     * @return array Collection of material identifiers by navigation identifiers
184
     */
185
    protected function findByNavigationIDs($entityIDs = array())
186
    {
187
        return (new MaterialNavigation($entityIDs))->idsByRelationID(static::$navigationIDs);
188
    }
189
190
    /**
191
     * Get collection of entity identifiers filtered by additional field and its value.
192
     *
193
     * @param Condition[] $additionalFields Collection of additional field identifiers => values
194
     * @param array $entityIDs Additional collection of entity identifiers for filtering
195
     * @return array Collection of material identifiers by navigation identifiers
196
     */
197
    protected function findByAdditionalFields($additionalFields, $entityIDs = array())
198
    {
199
        /**
200
         * TODO: We have separate request to materialfield for each field, maybe faster to
201
         * make one single query with all fields conditions. Performance tests are needed.
202
         */
203
204
        /** @var Condition $fieldCondition Iterate all additional fields needed for filter condition */
205
        foreach ($additionalFields as $fieldID => $fieldCondition) {
206
            // Get collection of entity identifiers passing already found identifiers
207
            $entityIDs = (new MaterialField($entityIDs))->idsByRelationID($fieldID, $fieldCondition, array());
208
209
            // Stop execution if we have no entities found at this step
210
            if (!count($entityIDs)) {
211
                break;
212
            }
213
        }
214
215
        return $entityIDs;
216
    }
217
218
    /**
219
     * @param array $entityIDs
220
     * @return array
221
     */
222
    protected function applySearch(array $entityIDs)
223
    {
224
        $condition = new Condition(ConditionInterface::DISJUNCTION);
225
226
        foreach ($this->searchFilter as $searchText) {
227
            foreach (static::$fieldValueColumns as $fieldId => $fieldColumn) {
228
                $condition->addCondition((new Condition())
229
                    ->addArgument(new Argument($fieldColumn, '%' . $searchText . '%', ArgumentInterface::LIKE))
230
                    ->addArgument(new Argument(\samsoncms\api\MaterialField::F_FIELDID, $fieldId)));
231
            }
232
        }
233
234
        return $this->query
235
            ->entity(\samsoncms\api\MaterialField::class)
236
            ->whereCondition($condition)
237
            ->where(Material::F_PRIMARY, $entityIDs)
238
            ->fields(Material::F_PRIMARY);
239
    }
240
241
    /**
242
     * Add sorting to entity identifiers.
243
     *
244
     * @param array $entityIDs
245
     * @param string $fieldName Additional field name for sorting
246
     * @param string $order Sorting order(ASC|DESC)
247
     * @return array Collection of entity identifiers ordered by additional field value
248
     */
249
    protected function applySorting(array $entityIDs, $fieldName, $order = 'ASC')
250
    {
251
        // Get additional field metadata
252
        $fieldID = &static::$fieldNames[$fieldName];
253
        $valueColumn = &static::$fieldValueColumns[$fieldID];
254
255
        // If this is additional field
256
        if (null !== $fieldID && null !== $valueColumn) {
257
            return $this->query
258
                ->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY)
259
                ->where(Field::F_PRIMARY, $fieldID)
260
                ->where(Material::F_PRIMARY, $entityIDs)
261
                ->orderBy($valueColumn, $order)
262
                ->fields(Material::F_PRIMARY);
263
        } else { // Nothing is changed
264
            return parent::applySorting($entityIDs, $fieldName, $order);
265
        }
266
    }
267
268
    /**
269
     * Get entities additional field values.
270
     *
271
     * @param array $entityIDs Collection of entity identifiers
272
     * @return array Collection of entities additional fields EntityID => [Additional field name => Value]
273
     * @throws EntityFieldNotFound
274
     */
275
    protected function findAdditionalFields($entityIDs)
276
    {
277
        $return = array();
278
279
        // Copy fields arrays
280
        $localized = static::$localizedFieldIDs;
281
        $notLocalized = static::$notLocalizedFieldIDs;
282
283
        // If we filter additional fields that we need to receive
284
        if (count($this->selectedFields)) {
285
            foreach ($this->selectedFields as $fieldID => $fieldName) {
286
                // Filter localized and not fields by selected fields
287
                if (!isset(static::$localizedFieldIDs[$fieldID])) {
288
                    unset($localized[$fieldID]);
289
                }
290
291
                if (!isset(static::$notLocalizedFieldIDs[$fieldID])) {
292
                    unset($notLocalized[$fieldID]);
293
                }
294
            }
295
        }
296
297
        // Prepare localized additional field query condition
298
        $condition = new Condition(Condition::DISJUNCTION);
299
        foreach ($localized as $fieldID => $fieldName) {
300
            $condition->addCondition(
301
                (new Condition())
302
                    ->add(Field::F_PRIMARY, $fieldID)
303
                    ->add(\samsoncms\api\MaterialField::F_LOCALE, $this->locale)
304
            );
305
        }
306
307
        // Prepare not localized fields condition
308
        foreach ($notLocalized as $fieldID => $fieldName) {
309
            $condition->add(Field::F_PRIMARY, $fieldID);
310
        }
311
312
        // Get additional fields values for current entity identifiers
313
        foreach ($this->query->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY)
0 ignored issues
show
Bug introduced by
The expression $this->query->entity(\sa...DELETION, true)->exec() of type boolean|array<integer,ob...k\orm\RecordInterface>> 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...
Coding Style introduced by
Space found before closing bracket of FOREACH loop
Loading history...
314
                     ->where(Material::F_PRIMARY, $entityIDs)
315
                     ->whereCondition($condition)
316
                     ->where(Material::F_DELETION, true)
317
                     ->exec() as $additionalField
318
        ) {
319
            // Get needed metadata
320
            $fieldID = $additionalField[Field::F_PRIMARY];
321
            $materialID = $additionalField[Material::F_PRIMARY];
322
            $valueField = &static::$fieldValueColumns[$fieldID];
323
            $fieldName = &static::$fieldIDs[$fieldID];
324
325
            // Check if we have this additional field in this entity query
326
            if (null === $valueField || null === $fieldName) {
327
                throw new EntityFieldNotFound($fieldID);
328
            } else { // Add field value to result
329
                $fieldValue = $additionalField[$valueField];
330
                // Gather additional fields values by entity identifiers and field name
331
                $return[$materialID][$fieldName] = $fieldValue;
332
            }
333
        }
334
335
        return $return;
336
    }
337
338
    /**
339
     * Fill entity additional fields.
340
     *
341
     * @param \samsoncms\api\Entity $entity Entity instance for filling
342
     * @param array $additionalFields Collection of additional field values
343
     * @return Entity With filled additional field values
344
     */
345
    protected function fillEntityFields(\samsoncms\api\Entity $entity, array $additionalFields)
346
    {
347
        // If we have list of additional fields that we need
348
        $fieldIDs = count($this->selectedFields) ? $this->selectedFields : static::$fieldIDs;
349
350
        // Iterate all entity additional fields
351
        foreach ($fieldIDs as $variable) {
352
            // Set only existing additional fields
353
            $pointer = &$additionalFields[$entity->id][$variable];
354
            if (null !== $pointer) {
355
                $entity->$variable = $pointer;
356
            }
357
        }
358
359
        return $entity;
360
    }
361
362
    /**
363
     * Perform SamsonCMS query and get collection of entities.
364
     *
365
     * @param int $page Page number
366
     * @param int $size Page size
367
     *
368
     * @return \samsoncms\api\Entity[] Collection of entity fields
369
     */
370
    public function find($page = null, $size = null)
371
    {
372
        $return = array();
373
        if (count($this->entityIDs = $this->findEntityIDs())) {
374
            $additionalFields = $this->findAdditionalFields($this->entityIDs);
375
376
            if (count($this->searchFilter)) {
377
                $this->entityIDs = $this->applySearch($this->entityIDs);
378
379
                // Return result if not ids
380
                if (count($this->entityIDs) === 0) {
381
                    return $return;
382
                }
383
            }
384
385
            // Slice identifier array to match pagination
386
            if (null !== $page && null !== $size) {
387
                $this->entityIDs = array_slice($this->entityIDs, ($page - 1) * $size, $size);
388
            }
389
390
            //elapsed('End fields values');
391
            /** @var \samsoncms\api\Entity $item Find entity instances */
392
            foreach (parent::find() as $item) {
393
                $item = $this->fillEntityFields($item, $additionalFields);
394
395
                // Store entity by identifier
396
                $return[$item[Material::F_PRIMARY]] = $item;
397
            }
398
        }
399
400
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
401
402
        return $return;
403
    }
404
405
    /**
406
     * Perform SamsonCMS query and get first matching entity.
407
     *
408
     * @return \samsoncms\api\Entity Firt matching entity
409
     */
410
    public function first()
411
    {
412
        $return = null;
413
        if (count($entityIDs = $this->findEntityIDs())) {
414
            $this->primary($entityIDs);
0 ignored issues
show
Documentation introduced by
$entityIDs is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
415
            $additionalFields = $this->findAdditionalFields($entityIDs);
416
417
            if (null !== ($foundEntity = parent::first())) {
418
                $return = $this->fillEntityFields($foundEntity, $additionalFields);
419
            }
420
        }
421
422
        return $return;
423
    }
424
425
    /**
426
     * Perform SamsonCMS query and get collection of entities fields.
427
     *
428
     * @param string $fieldName Entity field name
429
     * @return array Collection of entity fields
430
     * @throws EntityFieldNotFound
431
     */
432
    public function fields($fieldName)
433
    {
434
        $return = array();
435
        if (count($entityIDs = $this->findEntityIDs())) {
436
            // Check if our entity has this field
437
            $fieldID = &static::$fieldNames[$fieldName];
438
            if (isset($fieldID)) {
439
                $return = $this->query
440
                    ->entity(\samsoncms\api\MaterialField::ENTITY)
441
                    ->where(Material::F_PRIMARY, $entityIDs)
442
                    ->where(Field::F_PRIMARY, $fieldID)
443
                    ->where(\samsoncms\api\MaterialField::F_DELETION, true)
444
                    ->fields(static::$fieldValueColumns[$fieldID]);
445
            } elseif (array_key_exists($fieldName, static::$parentFields)) {
446
                // TODO: Generalize real and virtual entity fields and manipulations with them
447
                // Set filtered entity identifiers
448
                $this->where(Material::F_PRIMARY, $entityIDs);
0 ignored issues
show
Documentation introduced by
$entityIDs is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
449
                // If this is parent field
450
                return parent::fields($fieldName);
451
            } else {
452
                throw new EntityFieldNotFound($fieldName);
453
            }
454
        }
455
456
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
457
458
        return $return;
459
    }
460
461
    /**
462
     * Perform SamsonCMS query and get amount resulting entities.
463
     *
464
     * @return int Amount of resulting entities
465
     */
466
    public function count()
467
    {
468
        $return = 0;
0 ignored issues
show
Bug Compatibility introduced by
The expression 0; of type integer adds the type integer to the return on line 484 which is incompatible with the return type of the parent method samsoncms\api\query\Generic::count of type boolean|samsonframework\orm\RecordInterface.
Loading history...
469
        if (count($entityIDs = $this->findEntityIDs())) {
470
471
            if (count($this->searchFilter)) {
472
                $entityIDs = $this->applySearch($entityIDs);
473
474
                // Return result if not ids
475
                if (count($entityIDs) === 0) {
476
                    return 0;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return 0; (integer) is incompatible with the return type of the parent method samsoncms\api\query\Generic::count of type boolean|samsonframework\orm\RecordInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
477
                }
478
            }
479
480
            $this->primary($entityIDs);
0 ignored issues
show
Documentation introduced by
$entityIDs is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
481
            $return = parent::count();
482
        }
483
484
        return $return;
485
    }
486
487
    /**
488
     * Generic constructor.
489
     *
490
     * @param QueryInterface $query Database query instance
491
     * @param string $locale Query localization
492
     */
493
    public function __construct(QueryInterface $query = null, $locale = null)
494
    {
495
        $this->locale = $locale;
496
497
        parent::__construct(null === $query ? new dbQuery() : $query);
498
499
        // Work only with active entities
500
        $this->active(true);
501
    }
502
}
503