Completed
Push — master ( 1f9443...d13f8a )
by Vitaly
02:39
created

Entity::findByNavigationIDs()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
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 samsoncms\api\CMS;
11
use samsoncms\api\exception\EntityFieldNotFound;
12
use samsoncms\api\Field;
13
use samsoncms\api\Material;
14
use samsonframework\orm\ArgumentInterface;
15
use samsonframework\orm\Condition;
16
use samsonframework\orm\QueryInterface;
17
18
/**
19
 * Generic SamsonCMS Entity query.
20
 * @package samsoncms\api\query
21
 */
22
class Entity extends Generic
23
{
24
    /** @var array Collection of all additional fields names */
25
    public static $fieldNames = array();
26
27
    /** @var array Collection of localized additional fields identifiers */
28
    protected static $localizedFieldIDs = array();
29
30
    /** @var array Collection of NOT localized additional fields identifiers */
31
    protected static $notLocalizedFieldIDs = array();
32
33
    /** @var array Collection of all additional fields identifiers */
34
    protected static $fieldIDs = array();
35
36
    /** @var  @var array Collection of additional fields value column names */
37
    protected static $fieldValueColumns = array();
38
39
40
    /** @var array Collection of entity field filter */
41
    protected $fieldFilter = array();
42
43
    /** @var string Query locale */
44
    protected $locale = '';
45
46
    /** @var array Collection of limit parameters */
47
    protected $limit = array();
48
49
    /**
50
     * Select specified entity fields.
51
     * If this method is called then only selected entity fields
52
     * would be return in entity instances.
53
     *
54
     * @param mixed $fieldNames Entity field name or collection of names
55
     * @return $this Chaining
56
     */
57
    public function select($fieldNames)
58
    {
59
        // Convert argument to array and iterate
60
        foreach ((!is_array($fieldNames) ? array($fieldNames) : $fieldNames) as $fieldName) {
61
            // Try to find entity additional field
62
            $pointer = &static::$fieldNames[$fieldName];
63
            if (null !== $pointer) {
64
                // Store selected additional field buy FieldID and Field name
65
                $this->selectedFields[$pointer] = $fieldName;
66
            }
67
        }
68
69
        return $this;
70
    }
71
72
    /**
73
     * Set additional field for sorting.
74
     *
75
     * @param string $fieldName Additional field name
76
     * @param string $order Sorting order
77
     * @return $this Chaining
78
     */
79
    public function orderBy($fieldName, $order = 'ASC')
80
    {
81
        $this->orderBy = array($fieldName, $order);
82
83
        return $this;
84
    }
85
86
    /**
87
     * Set resulting query limits.
88
     *
89
     * @param integer $offset Starting index
90
     * @param integer|null $count Entities count
91
     * @return $this Chaining
92
     */
93
    public function limit($offset, $count = null)
94
    {
95
        $this->limit = array($offset, $count);
96
97
        return $this;
98
    }
99
100
    /**
101
     * Add condition to current query.
102
     *
103
     * @param string $fieldName Entity field name
104
     * @param string $fieldValue Value
105
     * @return $this Chaining
106
     */
107
    public function where($fieldName, $fieldValue = null, $fieldRelation = ArgumentInterface::EQUAL)
108
    {
109
        // Try to find entity additional field
110
        $pointer = &static::$fieldNames[$fieldName];
111
        if (isset($pointer)) {
112
            // Store additional field filter value
113
            $this->fieldFilter[$pointer] = $fieldValue;
114
        } else {
115
            parent::where($fieldName, $fieldValue, $fieldRelation);
116
        }
117
118
        return $this;
119
    }
120
121
    /** @return array Collection of entity identifiers */
122
    protected function findEntityIDs()
123
    {
124
        $entityIDs = array();
125
        if ($this->conditions) {
126
            $entityIDs = $this->query
127
                ->entity(Material::ENTITY)
128
                ->whereCondition($this->conditions)
129
                ->fields(Material::F_PRIMARY);
130
        }
131
132
        // TODO: Find and describe approach with maximum generic performance
133
        $entityIDs = $this->findByAdditionalFields(
134
            $this->fieldFilter,
135
            $this->findByNavigationIDs($entityIDs)
136
        );
137
138
        // Perform sorting if necessary
139
        if (count($this->orderBy) == 2) {
140
            $entityIDs = $this->applySorting($entityIDs, $this->orderBy[0], $this->orderBy[1]);
141
        }
142
143
        // Perform limits if necessary
144
        if (count($this->limit)) {
145
            $entityIDs = array_slice($entityIDs, $this->limit[0], $this->limit[1]);
146
        }
147
148
        return $entityIDs;
149
    }
150
151
    /**
152
     * Get collection of entity identifiers filtered by navigation identifiers.
153
     *
154
     * @param array $entityIDs Additional collection of entity identifiers for filtering
155
     * @return array Collection of material identifiers by navigation identifiers
156
     */
157
    protected function findByNavigationIDs($entityIDs = array())
158
    {
159
        return (new MaterialNavigation($entityIDs))->idsByRelationID(static::$navigationIDs);
160
    }
161
162
    /**
163
     * Get collection of entity identifiers filtered by additional field and its value.
164
     *
165
     * @param array $additionalFields Collection of additional field identifiers => values
166
     * @param array $entityIDs Additional collection of entity identifiers for filtering
167
     * @return array Collection of material identifiers by navigation identifiers
168
     */
169
    protected function findByAdditionalFields($additionalFields, $entityIDs = array())
170
    {
171
        /**
172
         * TODO: We have separate request to materialfield for each field, maybe faster to
173
         * make one single query with all fields conditions. Performance tests are needed.
174
         */
175
176
        // Iterate all additional fields needed for filter entity
177
        foreach ($additionalFields as $fieldID => $fieldValue) {
178
            // Get collection of entity identifiers passing already found identifiers
179
            $entityIDs = (new MaterialField($entityIDs))->idsByRelationID($fieldID, $fieldValue);
180
181
            // Stop execution if we have no entities found at this step
182
            if (!count($entityIDs)) {
183
                break;
184
            }
185
        }
186
187
        return $entityIDs;
188
    }
189
190
    /**
191
     * Add sorting to entity identifiers.
192
     *
193
     * @param array $entityIDs
194
     * @param string $fieldName Additional field name for sorting
195
     * @param string $order Sorting order(ASC|DESC)
196
     * @return array Collection of entity identifiers ordered by additional field value
197
     */
198
    protected function applySorting(array $entityIDs, $fieldName, $order = 'ASC')
199
    {
200
        // Get additional field metadata
201
        $fieldID = &static::$fieldNames[$fieldName];
202
        $valueColumn = &static::$fieldValueColumns[$fieldID];
203
204
        // If this is additional field
205
        if (null !== $fieldID && null !== $valueColumn) {
206
            return $this->query
207
                ->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY)
208
                ->where(Field::F_PRIMARY, $fieldID)
209
                ->where(Material::F_PRIMARY, $entityIDs)
210
                ->orderBy($valueColumn, $order)
211
                ->fields(Material::F_PRIMARY);
212
        } else { // Nothing is changed
213
            return $entityIDs;
214
        }
215
    }
216
217
    /**
218
     * Get entities additional field values.
219
     *
220
     * @param array $entityIDs Collection of entity identifiers
221
     * @return array Collection of entities additional fields EntityID => [Additional field name => Value]
222
     */
223
    protected function findAdditionalFields($entityIDs)
224
    {
225
        $return = array();
226
227
        // Copy fields arrays
228
        $localized = static::$localizedFieldIDs;
229
        $notLocalized = static::$notLocalizedFieldIDs;
230
231
        // If we filter additional fields that we need to receive
232
        if (count($this->selectedFields)) {
233
            foreach ($this->selectedFields as $fieldID => $fieldName) {
234
                // Filter localized and not fields by selected fields
235
                if (!isset(static::$localizedFieldIDs[$fieldID])) {
236
                    unset($localized[$fieldID]);
237
                }
238
239
                if (!isset(static::$notLocalizedFieldIDs[$fieldID])) {
240
                    unset($notLocalized[$fieldID]);
241
                }
242
            }
243
        }
244
245
        // Prepare localized additional field query condition
246
        $condition = new Condition(Condition::DISJUNCTION);
247
        foreach ($localized as $fieldID => $fieldName) {
248
            $condition->addCondition(
249
                (new Condition())
250
                    ->add(Field::F_PRIMARY, $fieldID)
251
                    ->add(\samsoncms\api\MaterialField::F_LOCALE, $this->locale)
252
            );
253
        }
254
255
        // Prepare not localized fields condition
256
        foreach ($notLocalized as $fieldID => $fieldName) {
257
            $condition->add(Field::F_PRIMARY, $fieldID);
258
        }
259
260
        // Get additional fields values for current entity identifiers
261
        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...
262
                     ->where(Material::F_PRIMARY, $entityIDs)
263
                     ->whereCondition($condition)
264
                     ->where(Material::F_DELETION, true)
265
                     ->exec() as $additionalField
266
        ) {
267
            // Get needed metadata
268
            $fieldID = $additionalField[Field::F_PRIMARY];
269
            $materialID = $additionalField[Material::F_PRIMARY];
270
            $valueField = &static::$fieldValueColumns[$fieldID];
271
            $fieldName = &static::$fieldIDs[$fieldID];
272
273
            // Check if we have this additional field in this entity query
274
            if (null === $valueField || null === $fieldName) {
275
                throw new EntityFieldNotFound($fieldID);
276
            } else { // Add field value to result
277
                $fieldValue = $additionalField[$valueField];
278
                // Gather additional fields values by entity identifiers and field name
279
                $return[$materialID][$fieldName] = $fieldValue;
280
            }
281
        }
282
283
        return $return;
284
    }
285
286
    /**
287
     * Fill entity additional fields.
288
     *
289
     * @param Entity $entity Entity instance for filling
290
     * @param array $additionalFields Collection of additional field values
291
     * @return Entity With filled additional field values
292
     */
293
    protected function fillEntityFields($entity, array $additionalFields)
294
    {
295
        // If we have list of additional fields that we need
296
        $fieldIDs = count($this->selectedFields) ? $this->selectedFields : static::$fieldIDs;
297
298
        // Iterate all entity additional fields
299
        foreach ($fieldIDs as $variable) {
300
            // Set only existing additional fields
301
            $pointer = &$additionalFields[$entity[Material::F_PRIMARY]][$variable];
302
            if (isset($pointer)) {
303
                $entity->$variable = $pointer;
304
            }
305
        }
306
307
        return $entity;
308
    }
309
310
    /**
311
     * Perform SamsonCMS query and get collection of entities.
312
     *
313
     * @param int $page Page number
314
     * @param int $size Page size
315
     *
316
     * @return \samsoncms\api\Entity[] Collection of entity fields
317
     */
318
    public function find($page = null, $size = null)
319
    {
320
        $return = array();
321
        if (count($entityIDs = $this->findEntityIDs())) {
322
            $additionalFields = $this->findAdditionalFields($entityIDs);
323
324
            // Slice identifier array to match pagination
325
            if (null !== $page && null !== $size) {
326
                $entityIDs = array_slice($entityIDs, ($page - 1) * $size, $size);
327
            }
328
329
            // Set entity primary keys
330
            $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...
331
332
            //elapsed('End fields values');
333
            /** @var \samsoncms\api\Entity $item Find entity instances */
334
            foreach (parent::find() as $item) {
0 ignored issues
show
Bug introduced by
The expression parent::find() 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...
335
                $item = $this->fillEntityFields($item, $additionalFields);
336
337
                // Store entity by identifier
338
                $return[$item[Material::F_PRIMARY]] = $item;
339
            }
340
        }
341
342
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
343
344
        return $return;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $return; (array) is incompatible with the return type of the parent method samsoncms\api\query\Generic::find 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...
345
    }
346
347
    /**
348
     * Perform SamsonCMS query and get first matching entity.
349
     *
350
     * @return \samsoncms\api\Entity Firt matching entity
351
     */
352
    public function first()
353
    {
354
        $return = array();
355
        if (count($entityIDs = $this->findEntityIDs())) {
356
            $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...
357
            $additionalFields = $this->findAdditionalFields($entityIDs);
358
            $return = $this->fillEntityFields(parent::first(), $additionalFields);
0 ignored issues
show
Documentation introduced by
parent::first() is of type object<samsoncms\api\Entity>|null, but the function expects a object<samsoncms\api\query\Entity>.

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...
359
        }
360
361
        return $return;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $return; (samsoncms\api\query\Entity|array) is incompatible with the return type of the parent method samsoncms\api\query\Generic::first of type samsoncms\api\Entity|null.

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...
362
    }
363
364
    /**
365
     * Perform SamsonCMS query and get collection of entities fields.
366
     *
367
     * @param string $fieldName Entity field name
368
     * @return array Collection of entity fields
369
     * @throws EntityFieldNotFound
370
     */
371
    public function fields($fieldName)
372
    {
373
        $return = array();
374
        if (count($entityIDs = $this->findEntityIDs())) {
375
            // Check if our entity has this field
376
            $fieldID = &static::$fieldNames[$fieldName];
377
            if (isset($fieldID)) {
378
                $return = $this->query
379
                    ->entity(\samsoncms\api\MaterialField::ENTITY)
380
                    ->where(Material::F_PRIMARY, $entityIDs)
381
                    ->where(Field::F_PRIMARY, $fieldID)
382
                    ->where(\samsoncms\api\MaterialField::F_DELETION, true)
383
                    ->fields(static::$fieldValueColumns[$fieldID]);
384
            } else {
385
                throw new EntityFieldNotFound($fieldName);
386
            }
387
        }
388
389
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
390
391
        return $return;
392
    }
393
394
    /**
395
     * Perform SamsonCMS query and get amount resulting entities.
396
     *
397
     * @return int Amount of resulting entities
398
     */
399
    public function count()
400
    {
401
        $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 407 which is incompatible with the return type of the parent method samsoncms\api\query\Generic::count of type boolean|samsonframework\orm\RecordInterface.
Loading history...
402
        if (count($entityIDs = $this->findEntityIDs())) {
403
            $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...
404
            $return = parent::count();
405
        }
406
407
        return $return;
408
    }
409
410
    /**
411
     * Generic constructor.
412
     *
413
     * @param QueryInterface $query Database query instance
414
     * @param string $locale Query localization
415
     */
416
    public function __construct(QueryInterface $query, $locale = NULL)
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
417
    {
418
        $this->locale = $locale;
419
420
        parent::__construct($query);
421
422
        // Work only with active entities
423
        $this->active(true);
424
    }
425
}
426