Completed
Push — master ( 8b3523...59b35b )
by Vitaly
03:42 queued 15s
created

Entity::limit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
rs 9.4286
cc 1
eloc 3
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
    /** @var array Collection of limit parameters */
50
    protected $limit = array();
51
52
    /**
53
     * Select specified entity fields.
54
     * If this method is called then only selected entity fields
55
     * would be return in entity instances.
56
     *
57
     * @param mixed $fieldNames Entity field name or collection of names
58
     * @return self Chaining
59
     */
60
    public function select($fieldNames)
61
    {
62
        // Convert argument to array and iterate
63
        foreach ((!is_array($fieldNames) ? array($fieldNames) : $fieldNames) as $fieldName) {
64
            // Try to find entity additional field
65
            $pointer = &static::$fieldNames[$fieldName];
66
            if (isset($pointer)) {
67
                // Store selected additional field buy FieldID and Field name
68
                $this->selectedFields[$pointer] = $fieldName;
69
            }
70
        }
71
72
        return $this;
73
    }
74
75
    /**
76
     * Set additional field for sorting.
77
     *
78
     * @param string $fieldName Additional field name
79
     * @param string $order Sorting order
80
     * @return self Chaining
81
     */
82
    public function orderBy($fieldName, $order = 'ASC')
83
    {
84
        $this->orderBy = array($fieldName, $order);
85
86
        return $this;
87
    }
88
89
    /**
90
     * Set resulting query limits.
91
     *
92
     * @param integer $offset Starting index
93
     * @param integer|null $count Entities count
94
     * @return self Chaining
95
     */
96
    public function limit($offset, $count = null)
97
    {
98
        $this->limit = array($offset, $count);
99
100
        return $this;
101
    }
102
103
    /**
104
     * Add condition to current query.
105
     *
106
     * @param string $fieldName Entity field name
107
     * @param string $fieldValue Value
108
     * @return self Chaining
109
     */
110
    public function where($fieldName, $fieldValue = null, $fieldRelation = ArgumentInterface::EQUAL)
111
    {
112
        // Try to find entity additional field
113
        $pointer = &static::$fieldNames[$fieldName];
114
        if (isset($pointer)) {
115
            // Store additional field filter value
116
            $this->fieldFilter[$pointer] = $fieldValue;
117
        } else {
118
            parent::where($fieldName, $fieldValue, $fieldRelation);
119
        }
120
121
        return $this;
122
    }
123
124
    /** @return array Collection of entity identifiers */
125
    protected function findEntityIDs()
126
    {
127
        // TODO: Find and describe approach with maximum generic performance
128
        $entityIDs = $this->findByAdditionalFields(
129
            $this->fieldFilter,
130
            $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...
131
        );
132
133
        // Perform sorting if necessary
134
        if (sizeof($this->orderBy) == 2) {
135
            $entityIDs = $this->applySorting($entityIDs, $this->orderBy[0], $this->orderBy[1]);
136
        }
137
138
        return $entityIDs;
139
    }
140
141
    /**
142
     * Get collection of entity identifiers filtered by navigation identifiers.
143
     *
144
     * @param array $entityIDs Additional collection of entity identifiers for filtering
145
     * @return array Collection of material identifiers by navigation identifiers
146
     */
147
    protected function findByNavigationIDs($entityIDs = array())
148
    {
149
        return (new MaterialNavigation($entityIDs))->idsByRelationID(static::$navigationIDs);
150
    }
151
152
    /**
153
     * Get collection of entity identifiers filtered by additional field and its value.
154
     *
155
     * @param array $additionalFields Collection of additional field identifiers => values
156
     * @param array $entityIDs Additional collection of entity identifiers for filtering
157
     * @return array Collection of material identifiers by navigation identifiers
158
     */
159
    protected function findByAdditionalFields($additionalFields, $entityIDs = array())
160
    {
161
        /**
162
         * TODO: We have separate request to materialfield for each field, maybe faster to
163
         * make one single query with all fields conditions. Performance tests are needed.
164
         */
165
166
        // Iterate all additional fields needed for filter entity
167
        foreach ($additionalFields as $fieldID => $fieldValue) {
168
            // Get collection of entity identifiers passing already found identifiers
169
            $entityIDs = (new MaterialField($entityIDs))->idsByRelationID($fieldID, $fieldValue);
170
171
            // Stop execution if we have no entities found at this step
172
            if (!sizeof($entityIDs)) {
173
                break;
174
            }
175
        }
176
177
        return $entityIDs;
178
    }
179
180
    /**
181
     * Add sorting to entity identifiers.
182
     *
183
     * @param array $entityIDs
184
     * @param string $fieldName Additional field name for sorting
185
     * @param string $order Sorting order(ASC|DESC)
186
     * @return array Collection of entity identifiers ordered by additional field value
187
     */
188
    protected function applySorting(array $entityIDs, $fieldName, $order = 'ASC')
189
    {
190
        // Get additional field metadata
191
        $fieldID = static::$fieldNames[$fieldName];
192
        $valueColumn = static::$fieldValueColumns[$fieldID];
193
194
        return $this->query
195
            ->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY)
196
            ->where(Field::F_PRIMARY, $fieldID)
197
            ->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...
198
            ->orderBy($valueColumn, $order)
199
            ->fields(Material::F_PRIMARY);
200
    }
201
202
    /**
203
     * Get entities additional field values.
204
     *
205
     * @param array $entityIDs Collection of entity identifiers
206
     * @return array Collection of entities additional fields EntityID => [Additional field name => Value]
207
     */
208
    protected function findAdditionalFields($entityIDs)
209
    {
210
        $return = array();
211
212
        // Copy fields arrays
213
        $localized = static::$localizedFieldIDs;
214
        $notLocalized = static::$notLocalizedFieldIDs;
215
216
        // If we filter additional fields that we need to receive
217
        if (sizeof($this->selectedFields)) {
218
            foreach ($this->selectedFields as $fieldID => $fieldName) {
219
                // Filter localized and not fields by selected fields
220
                if (!isset(static::$localizedFieldIDs[$fieldID])) {
221
                    unset($localized[$fieldID]);
222
                }
223
224
                if (!isset(static::$notLocalizedFieldIDs[$fieldID])) {
225
                    unset($notLocalized[$fieldID]);
226
                }
227
            }
228
        }
229
230
        // Prepare localized additional field query condition
231
        $condition = new Condition(Condition::DISJUNCTION);
232
        foreach ($localized as $fieldID => $fieldName) {
233
            $condition->addCondition(
234
                (new Condition())
235
                    ->add(Field::F_PRIMARY, $fieldID)
236
                    ->add(Field::F_LOCALIZED, $this->locale)
237
            );
238
        }
239
240
        // Prepare not localized fields condition
241
        foreach ($notLocalized as $fieldID => $fieldName) {
242
            $condition->add(Field::F_PRIMARY, $fieldID);
243
        }
244
245
        // Get additional fields values for current entity identifiers
246
        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|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...
Coding Style introduced by
Space found before closing bracket of FOREACH loop
Loading history...
247
                     ->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...
248
                     ->whereCondition($condition)
249
                     ->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...
250
                     ->exec() as $additionalField
251
        ) {
252
            // Get needed metadata
253
            $fieldID = $additionalField[Field::F_PRIMARY];
254
            $materialID = $additionalField[Material::F_PRIMARY];
255
            $valueField = static::$fieldValueColumns[$fieldID];
256
            $fieldName = static::$fieldIDs[$fieldID];
257
            $fieldValue = $additionalField[$valueField];
258
259
            // Gather additional fields values by entity identifiers and field name
260
            $return[$materialID][$fieldName] = $fieldValue;
261
        }
262
263
        return $return;
264
    }
265
266
    /**
267
     * Perform SamsonCMS query and get collection of entities.
268
     *
269
     * @return \samsoncms\api\Entity[] Collection of entity fields
270
     */
271
    public function find()
272
    {
273
        $return = array();
274
        if (sizeof($entityIDs = $this->findEntityIDs())) {
275
            $additionalFields = $this->findAdditionalFields($entityIDs);
276
277
            // Set entity primary keys
278
            $this->primary($entityIDs);
279
280
            //elapsed('End fields values');
281
            /** @var \samsoncms\api\Entity $item Find entity instances */
282
            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...
283
                // If we have list of additional fields that we need
284
                $fieldIDs = sizeof($this->selectedFields) ? $this->selectedFields : static::$fieldIDs;
285
286
                // Iterate all entity additional fields
287
                foreach ($fieldIDs as $variable) {
288
                    // Set only existing additional fields
289
                    $pointer = &$additionalFields[$item[Material::F_PRIMARY]][$variable];
290
                    if (isset($pointer)) {
291
                        $item->$variable = $pointer;
292
                    }
293
                }
294
                // Store entity by identifier
295
                $return[$item[Material::F_PRIMARY]] = $item;
296
            }
297
        }
298
299
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
300
301
        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...
302
    }
303
304
    /**
305
     * Perform SamsonCMS query and get first matching entity.
306
     *
307
     * @return \samsoncms\api\Entity Firt matching entity
308
     */
309
    public function first()
310
    {
311
        $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 318 which is incompatible with the return type documented by samsoncms\api\query\Entity::first of type samsoncms\api\Entity.
Loading history...
312
        if (sizeof($entityIDs = $this->findEntityIDs())) {
313
            $this->primary($entityIDs);
314
315
            $return = parent::first();
316
        }
317
318
        return $return;
319
    }
320
321
    /**
322
     * Perform SamsonCMS query and get collection of entities fields.
323
     *
324
     * @param string $fieldName Entity field name
325
     * @return array Collection of entity fields
326
     * @throws EntityFieldNotFound
327
     */
328
    public function fields($fieldName)
329
    {
330
        $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 348 which is incompatible with the return type of the parent method samsoncms\api\query\Generic::fields of type boolean|samsonframework\orm\RecordInterface.
Loading history...
331
        if (sizeof($entityIDs = $this->findEntityIDs())) {
332
            // Check if our entity has this field
333
            $fieldID = &static::$fieldNames[$fieldName];
334
            if (isset($fieldID)) {
335
                $return = $this->query
336
                    ->entity(\samsoncms\api\MaterialField::ENTITY)
337
                    ->where(Material::F_PRIMARY, $entityIDs)
338
                    ->where(Field::F_PRIMARY, $fieldID)
339
                    ->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...
340
                    ->fields(static::$fieldValueColumns[$fieldID]);
341
            } else {
342
                throw new EntityFieldNotFound($fieldName);
343
            }
344
        }
345
346
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
347
348
        return $return;
349
    }
350
351
    /**
352
     * Generic constructor.
353
     *
354
     * @param QueryInterface $query Database query instance
355
     * @param string $locale Query localizaation
356
     */
357
    public function __construct(QueryInterface $query, $locale = '')
358
    {
359
        $this->locale = $locale;
360
361
        parent::__construct($query);
362
    }
363
}
364