Completed
Push — master ( 9df172...8b3523 )
by Vitaly
04:12
created

Entity::orderBy()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
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
    protected 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 ordering parameters */
47
    protected $orderBy = 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 (isset($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
     */
78
    public function orderBy($fieldName, $order = 'ASC')
79
    {
80
        $this->orderBy = array($fieldName, $order);
81
    }
82
83
    /**
84
     * Add condition to current query.
85
     *
86
     * @param string $fieldName Entity field name
87
     * @param string $fieldValue Value
88
     * @return self Chaining
89
     */
90
    public function where($fieldName, $fieldValue = null, $fieldRelation = ArgumentInterface::EQUAL)
91
    {
92
        // Try to find entity additional field
93
        $pointer = &static::$fieldNames[$fieldName];
94
        if (isset($pointer)) {
95
            // Store additional field filter value
96
            $this->fieldFilter[$pointer] = $fieldValue;
97
        } else {
98
            parent::where($fieldName, $fieldValue, $fieldRelation);
99
        }
100
101
        return $this;
102
    }
103
104
    /** @return array Collection of entity identifiers */
105
    protected function findEntityIDs()
106
    {
107
        // TODO: Find and describe approach with maximum generic performance
108
        $entityIDs = $this->findByAdditionalFields(
109
            $this->fieldFilter,
110
            $this->findByNavigationIDs()
0 ignored issues
show
Documentation introduced by
$this->findByNavigationIDs() is of type boolean|object<samsonfra...rk\orm\RecordInterface>, but the function expects a array.

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...
111
        );
112
113
        // Perform sorting if necessary
114
        if (sizeof($this->orderBy) == 2) {
115
            $entityIDs = $this->applySorting($entityIDs, $this->orderBy[0], $this->orderBy[1]);
116
        }
117
118
        return $entityIDs;
119
    }
120
121
    /**
122
     * Get collection of entity identifiers filtered by navigation identifiers.
123
     *
124
     * @param array $entityIDs Additional collection of entity identifiers for filtering
125
     * @return array Collection of material identifiers by navigation identifiers
126
     */
127
    protected function findByNavigationIDs($entityIDs = array())
128
    {
129
        return (new MaterialNavigation($entityIDs))->idsByRelationID(static::$navigationIDs);
130
    }
131
132
    /**
133
     * Get collection of entity identifiers filtered by additional field and its value.
134
     *
135
     * @param array $additionalFields Collection of additional field identifiers => values
136
     * @param array $entityIDs Additional collection of entity identifiers for filtering
137
     * @return array Collection of material identifiers by navigation identifiers
138
     */
139
    protected function findByAdditionalFields($additionalFields, $entityIDs = array())
140
    {
141
        /**
142
         * TODO: We have separate request to materialfield for each field, maybe faster to
143
         * make one single query with all fields conditions. Performance tests are needed.
144
         */
145
146
        // Iterate all additional fields needed for filter entity
147
        foreach ($additionalFields as $fieldID => $fieldValue) {
148
            // Get collection of entity identifiers passing already found identifiers
149
            $entityIDs = (new MaterialField($entityIDs))->idsByRelationID($fieldID, $fieldValue);
150
151
            // Stop execution if we have no entities found at this step
152
            if (!sizeof($entityIDs)) {
153
                break;
154
            }
155
        }
156
157
        return $entityIDs;
158
    }
159
160
    /**
161
     * Add sorting to entity identifiers.
162
     *
163
     * @param array $entityIDs
164
     * @param string $fieldName Additional field name for sorting
165
     * @param string $order Sorting order(ASC|DESC)
166
     * @return array Collection of entity identifiers ordered by additional field value
167
     */
168
    protected function applySorting(array $entityIDs, $fieldName, $order = 'ASC')
169
    {
170
        // Get additional field metadata
171
        $fieldID = static::$fieldNames[$fieldName];
172
        $valueColumn = static::$fieldValueColumns[$fieldID];
173
174
        return $this->query
175
            ->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY)
176
            ->where(Field::F_PRIMARY, $fieldID)
177
            ->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...
178
            ->orderBy($valueColumn, $order)
179
            ->fields(Material::F_PRIMARY);
180
    }
181
182
    /**
183
     * Get entities additional field values.
184
     *
185
     * @param array $entityIDs Collection of entity identifiers
186
     * @return array Collection of entities additional fields EntityID => [Additional field name => Value]
187
     */
188
    protected function findAdditionalFields($entityIDs)
189
    {
190
        $return = array();
191
192
        // Copy fields arrays
193
        $localized = static::$localizedFieldIDs;
194
        $notLocalized = static::$notLocalizedFieldIDs;
195
196
        // If we filter additional fields that we need to receive
197
        if (sizeof($this->selectedFields)) {
198
            foreach ($this->selectedFields as $fieldID => $fieldName) {
199
                // Filter localized and not fields by selected fields
200
                if (!isset(static::$localizedFieldIDs[$fieldID])) {
201
                    unset($localized[$fieldID]);
202
                }
203
204
                if (!isset(static::$notLocalizedFieldIDs[$fieldID])) {
205
                    unset($notLocalized[$fieldID]);
206
                }
207
            }
208
        }
209
210
        // Prepare localized additional field query condition
211
        $condition = new Condition(Condition::DISJUNCTION);
212
        foreach ($localized as $fieldID => $fieldName) {
213
            $condition->addCondition(
214
                (new Condition())
215
                    ->add(Field::F_PRIMARY, $fieldID)
216
                    ->add(Field::F_LOCALIZED, $this->locale)
217
            );
218
        }
219
220
        // Prepare not localized fields condition
221
        foreach ($notLocalized as $fieldID => $fieldName) {
222
            $condition->add(Field::F_PRIMARY, $fieldID);
223
        }
224
225
        // Get additional fields values for current entity identifiers
226
        foreach ($this->query->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY)
0 ignored issues
show
Coding Style introduced by
Space found before closing bracket of FOREACH loop
Loading history...
Bug introduced by
The expression $this->query->entity(\sa...DELETION, true)->exec() of type boolean|object<samsonfra...rk\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...
227
                     ->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...
228
                     ->whereCondition($condition)
229
                     ->where(Material::F_DELETION, true)
0 ignored issues
show
Documentation introduced by
true is of type boolean, 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...
230
                     ->exec() as $additionalField
231
        ) {
232
            // Get needed metadata
233
            $fieldID = $additionalField[Field::F_PRIMARY];
234
            $materialID = $additionalField[Material::F_PRIMARY];
235
            $valueField = static::$fieldValueColumns[$fieldID];
236
            $fieldName = static::$fieldIDs[$fieldID];
237
            $fieldValue = $additionalField[$valueField];
238
239
            // Gather additional fields values by entity identifiers and field name
240
            $return[$materialID][$fieldName] = $fieldValue;
241
        }
242
243
        return $return;
244
    }
245
246
    /**
247
     * Perform SamsonCMS query and get collection of entities.
248
     *
249
     * @return \samsoncms\api\Entity[] Collection of entity fields
250
     */
251
    public function find()
252
    {
253
        $return = array();
254
        if (sizeof($entityIDs = $this->findEntityIDs())) {
255
            $additionalFields = $this->findAdditionalFields($entityIDs);
256
257
            // Set entity primary keys
258
            $this->primary($entityIDs);
259
260
            //elapsed('End fields values');
261
            /** @var \samsoncms\api\Entity $item Find entity instances */
262
            foreach (parent::find() as $item) {
0 ignored issues
show
Bug introduced by
The expression parent::find() of type boolean|object<samsonfra...rk\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...
263
                // If we have list of additional fields that we need
264
                $fieldIDs = sizeof($this->selectedFields) ? $this->selectedFields : static::$fieldIDs;
265
266
                // Iterate all entity additional fields
267
                foreach ($fieldIDs as $variable) {
268
                    // Set only existing additional fields
269
                    $pointer = &$additionalFields[$item[Material::F_PRIMARY]][$variable];
270
                    if (isset($pointer)) {
271
                        $item->$variable = $pointer;
272
                    }
273
                }
274
                // Store entity by identifier
275
                $return[$item[Material::F_PRIMARY]] = $item;
276
            }
277
        }
278
279
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
280
281
        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...
282
    }
283
284
    /**
285
     * Perform SamsonCMS query and get first matching entity.
286
     *
287
     * @return \samsoncms\api\Entity Firt matching entity
288
     */
289
    public function first()
290
    {
291
        $return = array();
0 ignored issues
show
Bug Compatibility introduced by
The expression array(); of type array adds the type array to the return on line 298 which is incompatible with the return type documented by samsoncms\api\query\Entity::first of type samsoncms\api\Entity.
Loading history...
292
        if (sizeof($entityIDs = $this->findEntityIDs())) {
293
            $this->primary($entityIDs);
294
295
            $return = parent::first();
296
        }
297
298
        return $return;
299
    }
300
301
    /**
302
     * Perform SamsonCMS query and get collection of entities fields.
303
     *
304
     * @param string $fieldName Entity field name
305
     * @return array Collection of entity fields
306
     * @throws EntityFieldNotFound
307
     */
308
    public function fields($fieldName)
309
    {
310
        $return = array();
0 ignored issues
show
Bug Compatibility introduced by
The expression array(); of type array adds the type array to the return on line 328 which is incompatible with the return type of the parent method samsoncms\api\query\Generic::fields of type boolean|samsonframework\orm\RecordInterface.
Loading history...
311
        if (sizeof($entityIDs = $this->findEntityIDs())) {
312
            // Check if our entity has this field
313
            $fieldID = &static::$fieldNames[$fieldName];
314
            if (isset($fieldID)) {
315
                $return = $this->query
316
                    ->entity(\samsoncms\api\MaterialField::ENTITY)
317
                    ->where(Material::F_PRIMARY, $entityIDs)
318
                    ->where(Field::F_PRIMARY, $fieldID)
319
                    ->where(\samsoncms\api\MaterialField::F_DELETION, true)
0 ignored issues
show
Documentation introduced by
true is of type boolean, 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...
320
                    ->fields(static::$fieldValueColumns[$fieldID]);
321
            } else {
322
                throw new EntityFieldNotFound($fieldName);
323
            }
324
        }
325
326
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
327
328
        return $return;
329
    }
330
331
    /**
332
     * Generic constructor.
333
     *
334
     * @param QueryInterface $query Database query instance
335
     * @param string $locale Query localizaation
336
     */
337
    public function __construct(QueryInterface $query, $locale = '')
338
    {
339
        $this->locale = $locale;
340
341
        parent::__construct($query);
342
    }
343
}
344