Completed
Push — master ( dbad2f...68a2d3 )
by Vitaly
02:40
created

EntityQuery::select()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
rs 9.2
cc 4
eloc 6
nc 3
nop 1
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\Field;
12
use samsonframework\orm\ArgumentInterface;
13
use samsonframework\orm\Condition;
14
use samsoncms\api\Material;
15
use samsonframework\orm\QueryInterface;
16
17
/**
18
 * Generic SamsonCMS Entity query.
19
 * @package samsoncms\api\query
20
 */
21
class EntityQuery extends Generic
22
{
23
    /** @var array Collection of all additional fields names */
24
    protected static $fieldNames = array();
25
26
    /** @var array Collection of localized additional fields identifiers */
27
    protected static $localizedFieldIDs = array();
28
29
    /** @var array Collection of NOT localized additional fields identifiers */
30
    protected static $notLocalizedFieldIDs = array();
31
32
    /** @var array Collection of all additional fields identifiers */
33
    protected static $fieldIDs = array();
34
35
    /** @var  @var array Collection of additional fields value column names */
36
    protected static $fieldValueColumns = array();
37
38
    /** @var array Collection of entity field filter */
39
    protected $fieldFilter = array();
40
41
    /** @var string Query locale */
42
    protected $locale = '';
43
44
    /**
45
     * Select specified entity fields.
46
     * If this method is called then only selected entity fields
47
     * would be return in entity instances.
48
     *
49
     * @param mixed $fieldNames Entity field name or collection of names
50
     * @return self Chaining
51
     */
52
    public function select($fieldNames)
53
    {
54
        // Convert argument to array and iterate
55
        foreach ((!is_array($fieldNames) ? array($fieldNames) : $fieldNames) as $fieldName) {
56
            // Try to find entity additional field
57
            $pointer = &static::$fieldNames[$fieldName];
58
            if (isset($pointer)) {
59
                // Store selected additional field buy FieldID and Field name
60
                $this->selectedFields[$pointer] = $fieldName;
61
            }
62
        }
63
64
        return $this;
65
    }
66
67
    /**
68
     * Add condition to current query.
69
     *
70
     * @param string $fieldName Entity field name
71
     * @param string $fieldValue Value
72
     * @return self Chaining
73
     */
74
    public function where($fieldName, $fieldValue = null, $fieldRelation = ArgumentInterface::EQUAL)
75
    {
76
        // Try to find entity additional field
77
        $pointer = &static::$fieldNames[$fieldName];
78
        if (isset($pointer)) {
79
            // Store additional field filter value
80
            $this->fieldFilter[$pointer] = $fieldValue;
81
        } else {
82
            parent::where($fieldName, $fieldValue, $fieldRelation);
83
        }
84
85
        return $this;
86
    }
87
88
    /** @return array Collection of entity identifiers */
89
    protected function findEntityIDs()
90
    {
91
        // TODO: Find and describe approach with maximum generic performance
92
        return $this->findByAdditionalFields(
93
            $this->fieldFilter,
94
            $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...
95
        );
96
    }
97
98
    /**
99
     * Get collection of entity identifiers filtered by navigation identifiers.
100
     *
101
     * @param array $entityIDs Additional collection of entity identifiers for filtering
102
     * @return array Collection of material identifiers by navigation identifiers
103
     */
104
    protected function findByNavigationIDs($entityIDs = array())
105
    {
106
        return (new MaterialNavigation($entityIDs))->idsByRelationID(static::$navigationIDs);
107
    }
108
109
    /**
110
     * Get collection of entity identifiers filtered by additional field and its value.
111
     *
112
     * @param array $additionalFields Collection of additional field identifiers => values
113
     * @param array $entityIDs Additional collection of entity identifiers for filtering
114
     * @return array Collection of material identifiers by navigation identifiers
115
     */
116
    protected function findByAdditionalFields($additionalFields, $entityIDs = array())
117
    {
118
        /**
119
         * TODO: We have separate request to materialfield for each field, maybe faster to
120
         * make one single query with all fields conditions. Performance tests are needed.
121
         */
122
123
        // Iterate all additional fields needed for filter entity
124
        foreach ($additionalFields as $fieldID => $fieldValue) {
125
            // Get collection of entity identifiers passing already found identifiers
126
            $entityIDs = (new MaterialField($entityIDs))->idsByRelationID($fieldID, $fieldValue);
127
128
            // Stop execution if we have no entities found at this step
129
            if (!sizeof($entityIDs)) {
130
                break;
131
            }
132
        }
133
134
        return $entityIDs;
135
    }
136
137
    /**
138
     * Get entities additional field values.
139
     *
140
     * @param array $entityIDs Collection of entity identifiers
141
     * @return array Collection of entities additional fields EntityID => [Additional field name => Value]
142
     */
143
    protected function findAdditionalFields($entityIDs)
144
    {
145
        $return = array();
146
147
        // Copy fields arrays
148
        $localized = static::$localizedFieldIDs;
149
        $notLocalized = static::$notLocalizedFieldIDs;
150
151
        // If we filter additional fields that we need to receive
152
        if (sizeof($this->selectedFields)) {
153
            foreach ($this->selectedFields as $fieldID => $fieldName) {
154
                // Filter localized and not fields by selected fields
155
                if (!isset(static::$localizedFieldIDs[$fieldID])) {
156
                    unset($localized[$fieldID]);
157
                }
158
159
                if (!isset(static::$notLocalizedFieldIDs[$fieldID])) {
160
                    unset($notLocalized[$fieldID]);
161
                }
162
            }
163
        }
164
165
        // Prepare localized additional field query condition
166
        $condition = new Condition(Condition::DISJUNCTION);
167
        foreach ($localized as $fieldID => $fieldName) {
168
            $condition->addCondition(
169
                (new Condition())
170
                    ->add(Field::F_PRIMARY, $fieldID)
171
                    ->add(Field::F_LOCALIZED, $this->locale)
172
            );
173
        }
174
175
        // Prepare not localized fields condition
176
        foreach ($notLocalized as $fieldID => $fieldName) {
177
            $condition->add(Field::F_PRIMARY, $fieldID);
178
        }
179
180
        // Get additional fields values for current entity identifiers
181
        foreach ($this->query->entity(\samsoncms\api\MaterialField::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...
182
                     ->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...
183
                     ->whereCondition($condition)
184
                     ->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...
185
                     ->exec() as $additionalField
186
        ) {
187
            // Get needed metadata
188
            $fieldID = $additionalField[Field::F_PRIMARY];
189
            $materialID = $additionalField[Material::F_PRIMARY];
190
            $valueField = static::$fieldValueColumns[$fieldID];
191
            $fieldName = static::$fieldIDs[$fieldID];
192
            $fieldValue = $additionalField[$valueField];
193
194
            // Gather additional fields values by entity identifiers and field name
195
            $return[$materialID][$fieldName] = $fieldValue;
196
        }
197
198
        return $return;
199
    }
200
201
    /**
202
     * Perform SamsonCMS query and get collection of entities.
203
     *
204
     * @return \samsoncms\api\Entity[] Collection of entity fields
205
     */
206
    public function find()
207
    {
208
        $return = array();
209
        if (sizeof($entityIDs = $this->findEntityIDs())) {
210
            $additionalFields = $this->findAdditionalFields($entityIDs);
211
212
            // Set entity primary keys
213
            $this->primary($entityIDs);
214
215
            //elapsed('End fields values');
216
            /** @var \samsoncms\api\Entity $item Find entity instances */
217
            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...
218
                // If we have list of additional fields that we need
219
                $fieldIDs = sizeof($this->selectedFields) ? $this->selectedFields : static::$fieldIDs;
220
221
                // Iterate all entity additional fields
222
                foreach ($fieldIDs as $variable) {
223
                    // Set only existing additional fields
224
                    $pointer = &$additionalFields[$item[Material::F_PRIMARY]][$variable];
225
                    if (isset($pointer)) {
226
                        $item->$variable = $pointer;
227
                    }
228
                }
229
                // Store entity by identifier
230
                $return[$item[Material::F_PRIMARY]] = $item;
231
            }
232
        }
233
234
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
235
236
        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...
237
    }
238
239
    /**
240
     * Perform SamsonCMS query and get first matching entity.
241
     *
242
     * @return \samsoncms\api\Entity Firt matching entity
243
     */
244
    public function first()
245
    {
246
        $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 253 which is incompatible with the return type documented by samsoncms\api\query\EntityQuery::first of type samsoncms\api\Entity.
Loading history...
247
        if (sizeof($entityIDs = $this->findEntityIDs())) {
248
            $this->primary($entityIDs);
249
250
            $return = parent::first();
251
        }
252
253
        return $return;
254
    }
255
256
    /**
257
     * Perform SamsonCMS query and get collection of entities fields.
258
     *
259
     * @param string $fieldName Entity field name
260
     * @return array Collection of entity fields
261
     * @throws EntityFieldNotFound
262
     */
263
    public function fields($fieldName)
264
    {
265
        $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 282 which is incompatible with the return type of the parent method samsoncms\api\query\Generic::fields of type boolean|samsonframework\orm\RecordInterface.
Loading history...
266
        if (sizeof($entityIDs = $this->findEntityIDs())) {
267
            // Check if our entity has this field
268
            $fieldID = &static::$fieldNames[$fieldName];
269
            if (isset($fieldID)) {
270
                $return = $this->query
271
                    ->entity(MaterialField::ENTITY)
272
                    ->where(Material::F_PRIMARY, $entityIDs)
273
                    ->where(Field::F_PRIMARY, $fieldID)
274
                    ->fields(static::$fieldValueColumns[$fieldID]);
275
            } else {
276
                throw new EntityFieldNotFound($fieldName);
277
            }
278
        }
279
280
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
281
282
        return $return;
283
    }
284
285
    /**
286
     * Generic constructor.
287
     *
288
     * @param QueryInterface $query Database query instance
289
     * @param string $locale Query localizaation
290
     */
291
    public function __construct(QueryInterface $query, $locale = '')
292
    {
293
        $this->locale = $locale;
294
295
        parent::__construct($query);
296
    }
297
}
298