Passed
Pull Request — master (#26)
by
unknown
02:32
created

Entity::count()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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