Completed
Pull Request — master (#74)
by getmanenko
03:26
created

Entity::find()   C

Complexity

Conditions 8
Paths 10

Size

Total Lines 39
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 4 Features 0
Metric Value
c 6
b 4
f 0
dl 0
loc 39
rs 5.3846
cc 8
eloc 15
nc 10
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 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\Argument;
16
use samsonframework\orm\ArgumentInterface;
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
     * Generic constructor.
56
     *
57
     * @param QueryInterface $query  Database query instance
58
     * @param string         $locale Query localization
59
     */
60
    public function __construct(QueryInterface $query = null, $locale = null)
61
    {
62
        $this->locale = $locale;
63
64
        parent::__construct(null === $query ? new dbQuery() : $query);
65
66
        // Work only with active entities
67
        $this->active(true);
68
    }
69
70
    /**
71
     * Select specified entity fields.
72
     * If this method is called then only selected entity fields
73
     * would be filled in entity instances.
74
     *
75
     * @param mixed $fieldNames Entity field name or collection of names
76
     *
77
*@return $this Chaining
78
     */
79 View Code Duplication
    public function select($fieldNames)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
80
    {
81
        // Convert argument to array and iterate
82
        foreach ((!is_array($fieldNames) ? array($fieldNames) : $fieldNames) as $fieldName) {
83
            // Try to find entity additional field
84
            $pointer = &static::$fieldNames[$fieldName];
85
            if (null !== $pointer) {
86
                // Store selected additional field buy FieldID and Field name
87
                $this->selectedFields[$pointer] = $fieldName;
88
            }
89
        }
90
91
        return $this;
92
    }
93
94
    /**
95
     * Set additional field for sorting.
96
     *
97
     * @param string $fieldName Additional field name
98
     * @param string $order Sorting order
99
     * @return $this Chaining
100
     */
101
    public function orderBy($fieldName, $order = 'ASC')
102
    {
103
        if (array_key_exists($fieldName, static::$fieldNames)) {
104
            $this->entityOrderBy = array($fieldName, $order);
105
        } else {
106
            parent::orderBy($fieldName, $order);
107
        }
108
109
        return $this;
110
    }
111
112
    /**
113
     * Search entity fields by text.
114
     *
115
     * @param string $text Searching text
116
     * @return $this
117
     */
118
    public function search($text)
119
    {
120
        $this->searchFilter[] = $text;
121
122
        return $this;
123
    }
124
125
    /**
126
     * Set resulting query limits.
127
     *
128
     * @param integer $offset Starting index
129
     * @param integer|null $count Entities count
130
     * @return $this Chaining
131
     */
132
    public function limit($offset, $count = null)
133
    {
134
        $this->limit = array($offset, $count);
135
136
        return $this;
137
    }
138
139
    /**
140
     * Perform SamsonCMS query and get collection of entities.
141
     *
142
     * @param int $page Page number
143
     * @param int $size Page size
144
     *
145
     * @return \samsoncms\api\Entity[] Collection of entity fields
146
     */
147
    public function find($page = null, $size = null)
148
    {
149
        $return = array();
150
        if (count($this->entityIDs = $this->findEntityIDs())) {
151
            // Apply search filter
152
            if (count($this->searchFilter)) {
153
                $this->entityIDs = $this->applySearch($this->entityIDs);
154
155
                // Return result if not ids
156
                if (count($this->entityIDs) === 0) {
157
                    return $return;
158
                }
159
            }
160
161
            // Slice identifier array to match pagination
162
            if (null !== $page && null !== $size) {
163
                $this->entityIDs = array_slice($this->entityIDs, ($page - 1) * $size, $size);
164
            }
165
166
            // Perform parent find() only if we have entity identifiers
167
            if (count($this->entityIDs)) {
168
                // Get entity additional field records
169
                $additionalFields = $this->findAdditionalFields($this->entityIDs);
170
171
                /** @var \samsoncms\api\Entity $item Find entity instances */
172
                foreach (parent::find() as $item) {
173
                    // Fill entity with additional fields
174
                    $item = $this->fillEntityFields($item, $additionalFields);
175
176
                    // Store entity by identifier
177
                    $return[$item[Material::F_PRIMARY]] = $item;
178
                }
179
            }
180
        }
181
182
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
183
184
        return $return;
185
    }
186
187
    /**
188
     * Prepare entity identifiers.
189
     *
190
     * @param array $entityIDs Collection of identifier for filtering
191
     * @return array Collection of entity identifiers
192
     */
193
    protected function findEntityIDs(array $entityIDs = array())
194
    {
195
        // TODO: Find and describe approach with maximum generic performance
196
197
        // Apply additional fields filtering first
198
        if (count($this->fieldFilter)) {
199
            $entityIDs = $this->findByAdditionalFields($this->fieldFilter, $entityIDs);
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...
200
        }
201
202
        // Apply navigation filtering secondly
203
        if (count($entityIDs) || !count($this->fieldFilter)) {
204
            $entityIDs = $this->findByNavigationIDs($entityIDs);
205
        }
206
207
        // TODO: Possible performance issue - from generated queries we are passing Active true and get all materials from DB
208
        if ($this->conditions) {
209
            $entityIDs = $this->query
210
                ->entity(Material::ENTITY)
211
                ->where(Material::F_PRIMARY, $entityIDs)
212
                ->whereCondition($this->conditions)
213
                ->fields(Material::F_PRIMARY);
214
        }
215
216
        // Perform sorting if necessary
217 View Code Duplication
        if (count($this->entityOrderBy) === 2) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
218
            $entityIDs = $this->applySorting($entityIDs, $this->entityOrderBy[0], $this->entityOrderBy[1]);
219
        }
220
221
        // Perform sorting in parent fields if necessary
222 View Code Duplication
        if (count($this->orderBy) === 2) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
223
            $entityIDs = $this->applySorting($entityIDs, $this->orderBy[0], $this->orderBy[1]);
224
        }
225
226
        // Perform limits if necessary
227
        if (count($this->limit)) {
228
            $entityIDs = array_slice($entityIDs, $this->limit[0], $this->limit[1]);
229
        }
230
231
        return $entityIDs;
232
    }
233
234
    /**
235
     * Get collection of entity identifiers filtered by additional field and its value.
236
     *
237
     * @param Condition[] $additionalFields Collection of additional field identifiers => values
238
     * @param array $entityIDs Additional collection of entity identifiers for filtering
239
     * @return array Collection of material identifiers by navigation identifiers
240
     */
241
    protected function findByAdditionalFields($additionalFields, $entityIDs = array())
242
    {
243
        /**
244
         * TODO: We have separate request to materialfield for each field, maybe faster to
245
         * make one single query with all fields conditions. Performance tests are needed.
246
         */
247
248
        /** @var Condition $fieldCondition Iterate all additional fields needed for filter condition */
249
        foreach ($additionalFields as $fieldID => $fieldCondition) {
250
            // Get collection of entity identifiers passing already found identifiers
251
            $entityIDs = (new MaterialField($entityIDs))->idsByRelationID($fieldID, $fieldCondition, array(), $this->locale);
252
253
            // Stop execution if we have no entities found at this step
254
            if (!count($entityIDs)) {
255
                break;
256
            }
257
        }
258
259
        return $entityIDs;
260
    }
261
262
    /**
263
     * Get collection of entity identifiers filtered by navigation identifiers.
264
     *
265
     * @param array $entityIDs Additional collection of entity identifiers for filtering
266
     *
267
     * @return array Collection of material identifiers by navigation identifiers
268
     */
269
    protected function findByNavigationIDs($entityIDs = array())
270
    {
271
        return (new MaterialNavigation($entityIDs))->idsByRelationID(static::$navigationIDs);
272
    }
273
274
    /**
275
     * Add sorting to entity identifiers.
276
     *
277
     * @param array $entityIDs
278
     * @param string $fieldName Additional field name for sorting
279
     * @param string $order Sorting order(ASC|DESC)
280
     * @return array Collection of entity identifiers ordered by additional field value
281
     */
282
    protected function applySorting(array $entityIDs, $fieldName, $order = 'ASC')
283
    {
284
        // Get additional field metadata
285
        $fieldID = &static::$fieldNames[$fieldName];
286
        $valueColumn = &static::$fieldValueColumns[$fieldID];
287
288
        // If this is additional field
289
        if (null !== $fieldID && null !== $valueColumn) {
290
            return $this->query
291
                ->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY)
292
                ->where(Field::F_PRIMARY, $fieldID)
293
                ->where(Material::F_PRIMARY, $entityIDs)
294
                ->orderBy($valueColumn, $order)
295
                ->fields(Material::F_PRIMARY);
296
        } else { // Nothing is changed
297
            return parent::applySorting($entityIDs, $fieldName, $order);
298
        }
299
    }
300
301
    /**
302
     * Get entities additional field values.
303
     *
304
     * @param array $entityIDs Collection of entity identifiers
305
     * @return array Collection of entities additional fields EntityID => [Additional field name => Value]
306
     * @throws EntityFieldNotFound
307
     */
308
    protected function findAdditionalFields($entityIDs)
309
    {
310
        $return = array();
311
312
        // Copy fields arrays
313
        $localized = static::$localizedFieldIDs;
314
        $notLocalized = static::$notLocalizedFieldIDs;
315
316
        // If we filter additional fields that we need to receive
317
        if (count($this->selectedFields)) {
318
            foreach ($this->selectedFields as $fieldID => $fieldName) {
319
                // Filter localized and not fields by selected fields
320
                if (!isset(static::$localizedFieldIDs[$fieldID])) {
321
                    unset($localized[$fieldID]);
322
                }
323
324
                if (!isset(static::$notLocalizedFieldIDs[$fieldID])) {
325
                    unset($notLocalized[$fieldID]);
326
                }
327
            }
328
        }
329
330
        // Prepare localized additional field query condition
331
        $condition = new Condition(Condition::DISJUNCTION);
332
        foreach ($localized as $fieldID => $fieldName) {
333
            $condition->addCondition(
334
                (new Condition())
335
                    ->add(Field::F_PRIMARY, $fieldID)
336
                    ->add(\samsoncms\api\MaterialField::F_LOCALE, $this->locale)
337
            );
338
        }
339
340
        // Prepare not localized fields condition
341
        foreach ($notLocalized as $fieldID => $fieldName) {
342
            $condition->add(Field::F_PRIMARY, $fieldID);
343
        }
344
345
        // Get additional fields values for current entity identifiers
346
        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...
347
                     ->where(Material::F_PRIMARY, $entityIDs)
348
                     ->whereCondition($condition)
349
                     ->where(Material::F_DELETION, true)
350
                     ->exec() as $additionalField
351
        ) {
352
            // Get needed metadata
353
            $fieldID = $additionalField[Field::F_PRIMARY];
354
            $materialID = $additionalField[Material::F_PRIMARY];
355
            $valueField = &static::$fieldValueColumns[$fieldID];
356
            $fieldName = &static::$fieldIDs[$fieldID];
357
358
            // Check if we have this additional field in this entity query
359
            if (null === $valueField || null === $fieldName) {
360
//                throw new EntityFieldNotFound($fieldID);
361
            } else { // Add field value to result
362
                $fieldValue = $additionalField[$valueField];
363
                // Gather additional fields values by entity identifiers and field name
364
                $return[$materialID][$fieldName] = $fieldValue;
365
            }
366
        }
367
368
        return $return;
369
    }
370
371
    /**
372
     * @param array $entityIDs
373
     *
374
     * @return array
375
     */
376
    protected function applySearch(array $entityIDs)
377
    {
378
        $condition = new Condition(ConditionInterface::DISJUNCTION);
379
380
        foreach ($this->searchFilter as $searchText) {
381
            foreach (static::$fieldValueColumns as $fieldId => $fieldColumn) {
382
                $condition->addCondition((new Condition())
383
                    ->addArgument(new Argument($fieldColumn, '%' . $searchText . '%', ArgumentInterface::LIKE))
384
                    ->addArgument(new Argument(\samsoncms\api\MaterialField::F_FIELDID, $fieldId)));
385
            }
386
        }
387
388
        return $this->query
389
            ->entity(\samsoncms\api\MaterialField::class)
390
            ->whereCondition($condition)
391
            ->where(Material::F_PRIMARY, $entityIDs)
392
            ->fields(Material::F_PRIMARY);
393
    }
394
395
    /**
396
     * Fill entity additional fields.
397
     *
398
     * @param \samsoncms\api\Entity $entity Entity instance for filling
399
     * @param array $additionalFields Collection of additional field values
400
     * @return Entity With filled additional field values
401
     */
402
    protected function fillEntityFields(\samsoncms\api\Entity $entity, array $additionalFields)
403
    {
404
        // If we have list of additional fields that we need
405
        $fieldIDs = count($this->selectedFields) ? $this->selectedFields : static::$fieldIDs;
406
407
        // Iterate all entity additional fields
408
        foreach ($fieldIDs as $variable) {
409
            // Set only existing additional fields
410
            $pointer = &$additionalFields[$entity->id][$variable];
411
            if (null !== $pointer) {
412
                $entity->$variable = $pointer;
413
            }
414
        }
415
416
        return $entity;
417
    }
418
419
    /**
420
     * Perform SamsonCMS query and get first matching entity.
421
     *
422
     * @return \samsoncms\api\Entity Firt matching entity
423
     */
424
    public function first()
425
    {
426
        $return = null;
427
        if (count($entityIDs = $this->findEntityIDs())) {
428
            $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...
429
            $additionalFields = $this->findAdditionalFields($entityIDs);
430
431
            if (null !== ($foundEntity = parent::first())) {
432
                $return = $this->fillEntityFields($foundEntity, $additionalFields);
433
            }
434
        }
435
436
        return $return;
437
    }
438
439
    /**
440
     * Perform SamsonCMS query and get collection of entities fields.
441
     *
442
     * @param string $fieldName Entity field name
443
     * @return array Collection of entity fields
444
     * @throws EntityFieldNotFound
445
     */
446
    public function fields($fieldName)
447
    {
448
        $return = array();
449
        if (count($entityIDs = $this->findEntityIDs())) {
450
            // Check if our entity has this field
451
            $fieldID = &static::$fieldNames[$fieldName];
452
            if (isset($fieldID)) {
453
                $return = $this->query
454
                    ->entity(\samsoncms\api\MaterialField::ENTITY)
455
                    ->where(Material::F_PRIMARY, $entityIDs)
456
                    ->where(Field::F_PRIMARY, $fieldID)
457
                    ->where(\samsoncms\api\MaterialField::F_DELETION, true)
458
                    ->fields(static::$fieldValueColumns[$fieldID]);
459
            } elseif (property_exists(static::$identifier, $fieldName)) {
460
                // TODO: Generalize real and virtual entity fields and manipulations with them
461
                // Set filtered entity identifiers
462
                $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...
463
                // If this is parent field
464
                return parent::fields($fieldName);
465
            } else {
466
                throw new EntityFieldNotFound($fieldName);
467
            }
468
        }
469
470
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
471
472
        return $return;
473
    }
474
475
    /**
476
     * Add condition to current query.
477
     *
478
     * @param string $fieldName     Entity field name
479
     * @param string $fieldValue    Value
480
     * @param string $fieldRelation Entity field to value relation
481
     *
482
     * @return $this Chaining
483
     */
484
    public function where($fieldName, $fieldValue = null, $fieldRelation = ArgumentInterface::EQUAL)
485
    {
486
        // TODO #1
487
        unset(static::$fieldNames['MaterialID']);
488
        // Try to find entity additional field
489
        if (array_key_exists($fieldName, static::$fieldNames)) {
490
            $pointer = static::$fieldNames[$fieldName];
491
            // Store additional field filter value
492
            $this->fieldFilter[$pointer] = (new Condition())->add(static::$fieldValueColumns[$pointer], $fieldValue, $fieldRelation);
493
        } else {
494
            parent::where($fieldName, $fieldValue, $fieldRelation);
495
        }
496
497
        return $this;
498
    }
499
500
    /**
501
     * Perform SamsonCMS query and get amount resulting entities.
502
     *
503
     * @return int Amount of resulting entities
504
     */
505
    public function count()
506
    {
507
        $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 523 which is incompatible with the return type of the parent method samsoncms\api\query\Record::count of type boolean|samsonframework\orm\RecordInterface.
Loading history...
508
        if (count($entityIDs = $this->findEntityIDs())) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
509
510
            if (count($this->searchFilter)) {
511
                $entityIDs = $this->applySearch($entityIDs);
512
513
                // Return result if not ids
514
                if (count($entityIDs) === 0) {
515
                    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\Record::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...
516
                }
517
            }
518
519
            $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...
520
            $return = parent::count();
521
        }
522
523
        return $return;
524
    }
525
}
526