Completed
Push — master ( 89322a...8cf2f6 )
by Vitaly
35:11 queued 20:23
created

Entity::find()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 28
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 3
Metric Value
c 4
b 1
f 3
dl 0
loc 28
rs 8.439
cc 5
eloc 11
nc 3
nop 2
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 self 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 self 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 self 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 self 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
        return $this->query
205
            ->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY)
206
            ->where(Field::F_PRIMARY, $fieldID)
207
            ->where(Material::F_PRIMARY, $entityIDs)
208
            ->orderBy($valueColumn, $order)
209
            ->fields(Material::F_PRIMARY);
210
    }
211
212
    /**
213
     * Get entities additional field values.
214
     *
215
     * @param array $entityIDs Collection of entity identifiers
216
     * @return array Collection of entities additional fields EntityID => [Additional field name => Value]
217
     */
218
    protected function findAdditionalFields($entityIDs)
219
    {
220
        $return = array();
221
222
        // Copy fields arrays
223
        $localized = static::$localizedFieldIDs;
224
        $notLocalized = static::$notLocalizedFieldIDs;
225
226
        // If we filter additional fields that we need to receive
227
        if (count($this->selectedFields)) {
228
            foreach ($this->selectedFields as $fieldID => $fieldName) {
229
                // Filter localized and not fields by selected fields
230
                if (!isset(static::$localizedFieldIDs[$fieldID])) {
231
                    unset($localized[$fieldID]);
232
                }
233
234
                if (!isset(static::$notLocalizedFieldIDs[$fieldID])) {
235
                    unset($notLocalized[$fieldID]);
236
                }
237
            }
238
        }
239
240
        // Prepare localized additional field query condition
241
        $condition = new Condition(Condition::DISJUNCTION);
242
        foreach ($localized as $fieldID => $fieldName) {
243
            $condition->addCondition(
244
                (new Condition())
245
                    ->add(Field::F_PRIMARY, $fieldID)
246
                    ->add(\samsoncms\api\MaterialField::F_LOCALE, $this->locale)
247
            );
248
        }
249
250
        // Prepare not localized fields condition
251
        foreach ($notLocalized as $fieldID => $fieldName) {
252
            $condition->add(Field::F_PRIMARY, $fieldID);
253
        }
254
255
        // Get additional fields values for current entity identifiers
256
        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...
257
                     ->where(Material::F_PRIMARY, $entityIDs)
258
                     ->whereCondition($condition)
259
                     ->where(Material::F_DELETION, true)
260
                     ->exec() as $additionalField
261
        ) {
262
            // Get needed metadata
263
            $fieldID = $additionalField[Field::F_PRIMARY];
264
            $materialID = $additionalField[Material::F_PRIMARY];
265
            $valueField = static::$fieldValueColumns[$fieldID];
266
            $fieldName = static::$fieldIDs[$fieldID];
267
            $fieldValue = $additionalField[$valueField];
268
269
            // Gather additional fields values by entity identifiers and field name
270
            $return[$materialID][$fieldName] = $fieldValue;
271
        }
272
273
        return $return;
274
    }
275
276
    /**
277
     * Fill entity additional fields.
278
     *
279
     * @param Entity $entity Entity instance for filling
280
     * @param array $additionalFields Collection of additional field values
281
     * @return Entity With filled additional field values
282
     */
283
    protected function fillEntityFields($entity, array $additionalFields)
284
    {
285
        // If we have list of additional fields that we need
286
        $fieldIDs = count($this->selectedFields) ? $this->selectedFields : static::$fieldIDs;
287
288
        // Iterate all entity additional fields
289
        foreach ($fieldIDs as $variable) {
290
            // Set only existing additional fields
291
            $pointer = &$additionalFields[$entity[Material::F_PRIMARY]][$variable];
292
            if (isset($pointer)) {
293
                $entity->$variable = $pointer;
294
            }
295
        }
296
297
        return $entity;
298
    }
299
300
    /**
301
     * Perform SamsonCMS query and get collection of entities.
302
     *
303
     * @param int $page Page number
304
     * @param int $size Page size
305
     *
306
     * @return \samsoncms\api\Entity[] Collection of entity fields
307
     */
308
    public function find($page = null, $size = null)
309
    {
310
        $return = array();
311
        if (count($entityIDs = $this->findEntityIDs())) {
312
            $additionalFields = $this->findAdditionalFields($entityIDs);
313
314
            // Slice identifier array to match pagination
315
            if (null !== $page && null !== $size) {
316
                $entityIDs = array_slice($entityIDs, ($page - 1) * $size, $size);
317
            }
318
319
            // Set entity primary keys
320
            $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...
321
322
            //elapsed('End fields values');
323
            /** @var \samsoncms\api\Entity $item Find entity instances */
324
            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...
325
                $item = $this->fillEntityFields($item, $additionalFields);
326
327
                // Store entity by identifier
328
                $return[$item[Material::F_PRIMARY]] = $item;
329
            }
330
        }
331
332
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
333
334
        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...
335
    }
336
337
    /**
338
     * Perform SamsonCMS query and get first matching entity.
339
     *
340
     * @return \samsoncms\api\Entity Firt matching entity
341
     */
342
    public function first()
343
    {
344
        $return = array();
345
        if (count($entityIDs = $this->findEntityIDs())) {
346
            $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...
347
            $additionalFields = $this->findAdditionalFields($entityIDs);
348
            $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...
349
        }
350
351
        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...
352
    }
353
354
    /**
355
     * Perform SamsonCMS query and get collection of entities fields.
356
     *
357
     * @param string $fieldName Entity field name
358
     * @return array Collection of entity fields
359
     * @throws EntityFieldNotFound
360
     */
361
    public function fields($fieldName)
362
    {
363
        $return = array();
364
        if (count($entityIDs = $this->findEntityIDs())) {
365
            // Check if our entity has this field
366
            $fieldID = &static::$fieldNames[$fieldName];
367
            if (isset($fieldID)) {
368
                $return = $this->query
369
                    ->entity(\samsoncms\api\MaterialField::ENTITY)
370
                    ->where(Material::F_PRIMARY, $entityIDs)
371
                    ->where(Field::F_PRIMARY, $fieldID)
372
                    ->where(\samsoncms\api\MaterialField::F_DELETION, true)
373
                    ->fields(static::$fieldValueColumns[$fieldID]);
374
            } else {
375
                throw new EntityFieldNotFound($fieldName);
376
            }
377
        }
378
379
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
380
381
        return $return;
382
    }
383
384
    /**
385
     * Perform SamsonCMS query and get amount resulting entities.
386
     *
387
     * @return int Amount of resulting entities
388
     */
389
    public function count()
390
    {
391
        $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 397 which is incompatible with the return type of the parent method samsoncms\api\query\Generic::count of type boolean|samsonframework\orm\RecordInterface.
Loading history...
392
        if (count($entityIDs = $this->findEntityIDs())) {
393
            $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...
394
            $return = parent::count();
395
        }
396
397
        return $return;
398
    }
399
400
    /**
401
     * Generic constructor.
402
     *
403
     * @param QueryInterface $query Database query instance
404
     * @param string $locale Query localization
405
     */
406
    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...
407
    {
408
        $this->locale = $locale;
409
410
        parent::__construct($query);
411
412
        // Work only with active entities
413
        $this->active(true);
414
    }
415
}
416