Passed
Push — master ( 1cb81b...ba037c )
by Vitaly
05:38 queued 02:39
created

Entity::applySorting()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 25
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 2 Features 0
Metric Value
c 3
b 2
f 0
dl 0
loc 25
rs 8.5806
cc 4
eloc 18
nc 3
nop 3
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
        if (count($this->entityOrderBy) === 2) {
163
            $entityIDs = $this->applySorting($entityIDs, $this->entityOrderBy[0], $this->entityOrderBy[1]);
164
        }
165
166
        // Perform limits if necessary
167
        if (count($this->limit)) {
168
            $entityIDs = array_slice($entityIDs, $this->limit[0], $this->limit[1]);
169
        }
170
171
        return $entityIDs;
172
    }
173
174
    /**
175
     * Get collection of entity identifiers filtered by navigation identifiers.
176
     *
177
     * @param array $entityIDs Additional collection of entity identifiers for filtering
178
     * @return array Collection of material identifiers by navigation identifiers
179
     */
180
    protected function findByNavigationIDs($entityIDs = array())
181
    {
182
        return (new MaterialNavigation($entityIDs))->idsByRelationID(static::$navigationIDs);
183
    }
184
185
    /**
186
     * Get collection of entity identifiers filtered by additional field and its value.
187
     *
188
     * @param Condition[] $additionalFields Collection of additional field identifiers => values
189
     * @param array $entityIDs Additional collection of entity identifiers for filtering
190
     * @return array Collection of material identifiers by navigation identifiers
191
     */
192
    protected function findByAdditionalFields($additionalFields, $entityIDs = array())
193
    {
194
        /**
195
         * TODO: We have separate request to materialfield for each field, maybe faster to
196
         * make one single query with all fields conditions. Performance tests are needed.
197
         */
198
199
        /** @var Condition $fieldCondition Iterate all additional fields needed for filter condition */
200
        foreach ($additionalFields as $fieldID => $fieldCondition) {
201
            // Get collection of entity identifiers passing already found identifiers
202
            $entityIDs = (new MaterialField($entityIDs))->idsByRelationID($fieldID, $fieldCondition, array());
203
204
            // Stop execution if we have no entities found at this step
205
            if (!count($entityIDs)) {
206
                break;
207
            }
208
        }
209
210
        return $entityIDs;
211
    }
212
213
    /**
214
     * @param array $entityIDs
215
     * @return array
216
     */
217
    protected function applySearch(array $entityIDs)
218
    {
219
        $condition = new Condition(ConditionInterface::DISJUNCTION);
220
221
        foreach ($this->searchFilter as $searchText) {
222
            foreach (static::$fieldValueColumns as $fieldId => $fieldColumn) {
223
                $condition->addCondition((new Condition())
224
                    ->addArgument(new Argument($fieldColumn, '%' . $searchText . '%', ArgumentInterface::LIKE))
225
                    ->addArgument(new Argument(\samsoncms\api\MaterialField::F_FIELDID, $fieldId)));
226
            }
227
        }
228
229
        return $this->query
230
            ->entity(\samsoncms\api\MaterialField::class)
231
            ->whereCondition($condition)
232
            ->where(Material::F_PRIMARY, $entityIDs)
233
            ->fields(Material::F_PRIMARY);
234
    }
235
236
    /**
237
     * Add sorting to entity identifiers.
238
     *
239
     * @param array $entityIDs
240
     * @param string $fieldName Additional field name for sorting
241
     * @param string $order Sorting order(ASC|DESC)
242
     * @return array Collection of entity identifiers ordered by additional field value
243
     */
244
    protected function applySorting(array $entityIDs, $fieldName, $order = 'ASC')
245
    {
246
        // Get additional field metadata
247
        $fieldID = &static::$fieldNames[$fieldName];
248
        $valueColumn = &static::$fieldValueColumns[$fieldID];
249
250
        // If this is additional field
251
        if (null !== $fieldID && null !== $valueColumn) {
252
            return $this->query
253
                ->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY)
254
                ->where(Field::F_PRIMARY, $fieldID)
255
                ->where(Material::F_PRIMARY, $entityIDs)
256
                ->orderBy($valueColumn, $order)
257
                ->fields(Material::F_PRIMARY);
258
        } elseif (array_key_exists($fieldName, static::$parentFields)) {
259
            // Order by parent fields
260
            return $this->query
261
                ->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY)
262
                ->where(Material::F_PRIMARY, $entityIDs)
263
                ->orderBy($fieldName, $order)
264
                ->fields(Material::F_PRIMARY);
265
        } else { // Nothing is changed
266
            return $entityIDs;
267
        }
268
    }
269
270
    /**
271
     * Get entities additional field values.
272
     *
273
     * @param array $entityIDs Collection of entity identifiers
274
     * @return array Collection of entities additional fields EntityID => [Additional field name => Value]
275
     */
276
    protected function findAdditionalFields($entityIDs)
277
    {
278
        $return = array();
279
280
        // Copy fields arrays
281
        $localized = static::$localizedFieldIDs;
282
        $notLocalized = static::$notLocalizedFieldIDs;
283
284
        // If we filter additional fields that we need to receive
285
        if (count($this->selectedFields)) {
286
            foreach ($this->selectedFields as $fieldID => $fieldName) {
287
                // Filter localized and not fields by selected fields
288
                if (!isset(static::$localizedFieldIDs[$fieldID])) {
289
                    unset($localized[$fieldID]);
290
                }
291
292
                if (!isset(static::$notLocalizedFieldIDs[$fieldID])) {
293
                    unset($notLocalized[$fieldID]);
294
                }
295
            }
296
        }
297
298
        // Prepare localized additional field query condition
299
        $condition = new Condition(Condition::DISJUNCTION);
300
        foreach ($localized as $fieldID => $fieldName) {
301
            $condition->addCondition(
302
                (new Condition())
303
                    ->add(Field::F_PRIMARY, $fieldID)
304
                    ->add(\samsoncms\api\MaterialField::F_LOCALE, $this->locale)
305
            );
306
        }
307
308
        // Prepare not localized fields condition
309
        foreach ($notLocalized as $fieldID => $fieldName) {
310
            $condition->add(Field::F_PRIMARY, $fieldID);
311
        }
312
313
        // Get additional fields values for current entity identifiers
314
        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...
315
                     ->where(Material::F_PRIMARY, $entityIDs)
316
                     ->whereCondition($condition)
317
                     ->where(Material::F_DELETION, true)
318
                     ->exec() as $additionalField
319
        ) {
320
            // Get needed metadata
321
            $fieldID = $additionalField[Field::F_PRIMARY];
322
            $materialID = $additionalField[Material::F_PRIMARY];
323
            $valueField = &static::$fieldValueColumns[$fieldID];
324
            $fieldName = &static::$fieldIDs[$fieldID];
325
326
            // Check if we have this additional field in this entity query
327
            if (null === $valueField || null === $fieldName) {
328
                throw new EntityFieldNotFound($fieldID);
329
            } else { // Add field value to result
330
                $fieldValue = $additionalField[$valueField];
331
                // Gather additional fields values by entity identifiers and field name
332
                $return[$materialID][$fieldName] = $fieldValue;
333
            }
334
        }
335
336
        return $return;
337
    }
338
339
    /**
340
     * Fill entity additional fields.
341
     *
342
     * @param Entity $entity Entity instance for filling
343
     * @param array $additionalFields Collection of additional field values
344
     * @return Entity With filled additional field values
345
     */
346
    protected function fillEntityFields($entity, array $additionalFields)
347
    {
348
        // If we have list of additional fields that we need
349
        $fieldIDs = count($this->selectedFields) ? $this->selectedFields : static::$fieldIDs;
350
351
        // Iterate all entity additional fields
352
        foreach ($fieldIDs as $variable) {
353
            // Set only existing additional fields
354
            $pointer = &$additionalFields[$entity[Material::F_PRIMARY]][$variable];
355
            if (isset($pointer)) {
356
                $entity->$variable = $pointer;
357
            }
358
        }
359
360
        return $entity;
361
    }
362
363
    /**
364
     * Perform SamsonCMS query and get collection of entities.
365
     *
366
     * @param int $page Page number
367
     * @param int $size Page size
368
     *
369
     * @return \samsoncms\api\Entity[] Collection of entity fields
370
     */
371
    public function find($page = null, $size = null)
372
    {
373
        $return = array();
374
        if (count($entityIDs = $this->findEntityIDs())) {
375
            $additionalFields = $this->findAdditionalFields($entityIDs);
376
377 View Code Duplication
            if (count($this->searchFilter)) {
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...
378
                $entityIDs = $this->applySearch($entityIDs);
379
380
                // Return result if not ids
381
                if (count($entityIDs) === 0) {
382
                    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...
383
                }
384
            }
385
386
387
388
            // Slice identifier array to match pagination
389
            if (null !== $page && null !== $size) {
390
                $entityIDs = array_slice($entityIDs, ($page - 1) * $size, $size);
391
            }
392
393
            // Set entity primary keys
394
            $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...
395
396
            //elapsed('End fields values');
397
            /** @var \samsoncms\api\Entity $item Find entity instances */
398
            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...
399
                $item = $this->fillEntityFields($item, $additionalFields);
400
401
                // Store entity by identifier
402
                $return[$item[Material::F_PRIMARY]] = $item;
403
            }
404
        }
405
406
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
407
408
        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...
409
    }
410
411
    /**
412
     * Perform SamsonCMS query and get first matching entity.
413
     *
414
     * @return \samsoncms\api\Entity Firt matching entity
415
     */
416
    public function first()
417
    {
418
        $return = array();
419
        if (count($entityIDs = $this->findEntityIDs())) {
420
            $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...
421
            $additionalFields = $this->findAdditionalFields($entityIDs);
422
            $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...
423
        }
424
425
        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...
426
    }
427
428
    /**
429
     * Perform SamsonCMS query and get collection of entities fields.
430
     *
431
     * @param string $fieldName Entity field name
432
     * @return array Collection of entity fields
433
     * @throws EntityFieldNotFound
434
     */
435
    public function fields($fieldName)
436
    {
437
        $return = array();
438
        if (count($entityIDs = $this->findEntityIDs())) {
439
            // Check if our entity has this field
440
            $fieldID = &static::$fieldNames[$fieldName];
441
            if (isset($fieldID)) {
442
                $return = $this->query
443
                    ->entity(\samsoncms\api\MaterialField::ENTITY)
444
                    ->where(Material::F_PRIMARY, $entityIDs)
445
                    ->where(Field::F_PRIMARY, $fieldID)
446
                    ->where(\samsoncms\api\MaterialField::F_DELETION, true)
447
                    ->fields(static::$fieldValueColumns[$fieldID]);
448
            } elseif (array_key_exists($fieldName, static::$parentFields)) {
449
                // TODO: Generalize real and virtual entity fields and manipulations with them
450
                // Set filtered entity identifiers
451
                $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...
452
                // If this is parent field
453
                return parent::fields($fieldName);
454
            } else {
455
                throw new EntityFieldNotFound($fieldName);
456
            }
457
        }
458
459
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
460
461
        return $return;
462
    }
463
464
    /**
465
     * Perform SamsonCMS query and get amount resulting entities.
466
     *
467
     * @return int Amount of resulting entities
468
     */
469
    public function count()
470
    {
471
        $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 487 which is incompatible with the return type of the parent method samsoncms\api\query\Generic::count of type boolean|samsonframework\orm\RecordInterface.
Loading history...
472
        if (count($entityIDs = $this->findEntityIDs())) {
473
474 View Code Duplication
            if (count($this->searchFilter)) {
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...
475
                $entityIDs = $this->applySearch($entityIDs);
476
477
                // Return result if not ids
478
                if (count($entityIDs) === 0) {
479
                    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...
480
                }
481
            }
482
483
            $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...
484
            $return = parent::count();
485
        }
486
487
        return $return;
488
    }
489
490
    /**
491
     * Generic constructor.
492
     *
493
     * @param QueryInterface $query Database query instance
494
     * @param string $locale Query localization
495
     */
496
    public function __construct(QueryInterface $query = null, $locale = null)
497
    {
498
        $this->locale = $locale;
499
500
        parent::__construct(null === $query ? new dbQuery() : $query);
501
502
        // Work only with active entities
503
        $this->active(true);
504
    }
505
}
506