Completed
Push — master ( 389190...0e7ec8 )
by Vitaly
02:49
created

Entity::save()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 11
rs 9.4286
cc 2
eloc 6
nc 2
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
    protected function localizedFieldsCondition($fieldIDs, $locale)
0 ignored issues
show
Unused Code introduced by
The parameter $locale is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
53
    {
54
        // Prepare localized additional field query condition
55
        $condition = new Condition(Condition::DISJUNCTION);
56 View Code Duplication
        foreach ($fieldIDs as $fieldID => $fieldName) {
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...
57
            $condition->addCondition(
58
                (new Condition())
59
                    ->add(Field::F_PRIMARY, $fieldID)
60
                    ->add(Field::F_LOCALIZED, $this->locale)
61
            );
62
        }
63
64
        return $condition;
65
    }
66
67
    public function save(\samsoncms\api\Entity &$instance, $locale = null)
0 ignored issues
show
Unused Code introduced by
The parameter $locale is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
68
    {
69
        $this->query->entity(\samsoncms\api\MaterialField::ENTITY)
70
            ->where(\samsoncms\api\Field::F_PRIMARY, array_keys(static::$fieldIDs))
71
            ->where(\samsoncms\api\Material::F_PRIMARY, $instance->id)
72
            ->exec();
73
74
        foreach (static::$fieldIDs as $fieldID => $fieldName) {
75
76
        }
77
    }
78
79
80
    /**
81
     * Select specified entity fields.
82
     * If this method is called then only selected entity fields
83
     * would be return in entity instances.
84
     *
85
     * @param mixed $fieldNames Entity field name or collection of names
86
     * @return self Chaining
87
     */
88
    public function select($fieldNames)
89
    {
90
        // Convert argument to array and iterate
91
        foreach ((!is_array($fieldNames) ? array($fieldNames) : $fieldNames) as $fieldName) {
92
            // Try to find entity additional field
93
            $pointer = &static::$fieldNames[$fieldName];
94
            if (isset($pointer)) {
95
                // Store selected additional field buy FieldID and Field name
96
                $this->selectedFields[$pointer] = $fieldName;
97
            }
98
        }
99
100
        return $this;
101
    }
102
103
    /**
104
     * Set additional field for sorting.
105
     *
106
     * @param string $fieldName Additional field name
107
     * @param string $order Sorting order
108
     * @return self Chaining
109
     */
110
    public function orderBy($fieldName, $order = 'ASC')
111
    {
112
        $this->orderBy = array($fieldName, $order);
113
114
        return $this;
115
    }
116
117
    /**
118
     * Set resulting query limits.
119
     *
120
     * @param integer $offset Starting index
121
     * @param integer|null $count Entities count
122
     * @return self Chaining
123
     */
124
    public function limit($offset, $count = null)
125
    {
126
        $this->limit = array($offset, $count);
127
128
        return $this;
129
    }
130
131
    /**
132
     * Add condition to current query.
133
     *
134
     * @param string $fieldName Entity field name
135
     * @param string $fieldValue Value
136
     * @return self Chaining
137
     */
138
    public function where($fieldName, $fieldValue = null, $fieldRelation = ArgumentInterface::EQUAL)
139
    {
140
        // Try to find entity additional field
141
        $pointer = &static::$fieldNames[$fieldName];
142
        if (isset($pointer)) {
143
            // Store additional field filter value
144
            $this->fieldFilter[$pointer] = $fieldValue;
145
        } else {
146
            parent::where($fieldName, $fieldValue, $fieldRelation);
147
        }
148
149
        return $this;
150
    }
151
152
    /** @return array Collection of entity identifiers */
153
    protected function findEntityIDs()
154
    {
155
        $entityIDs = array();
156
        if ($this->conditions) {
157
            $entityIDs = $this->query
158
                ->entity(Material::ENTITY)
159
                ->whereCondition($this->conditions)
160
                ->fields(Material::F_PRIMARY);
161
        }
162
163
        // TODO: Find and describe approach with maximum generic performance
164
        $entityIDs = $this->findByAdditionalFields(
165
            $this->fieldFilter,
166
            $this->findByNavigationIDs($entityIDs)
167
        );
168
169
        // Perform sorting if necessary
170
        if (sizeof($this->orderBy) == 2) {
171
            $entityIDs = $this->applySorting($entityIDs, $this->orderBy[0], $this->orderBy[1]);
172
        }
173
174
        // Perform limits if necessary
175
        if (sizeof($this->limit)) {
176
            $entityIDs = array_slice($entityIDs, $this->limit[0], $this->limit[1]);
177
        }
178
179
        return $entityIDs;
180
    }
181
182
    /**
183
     * Get collection of entity identifiers filtered by navigation identifiers.
184
     *
185
     * @param array $entityIDs Additional collection of entity identifiers for filtering
186
     * @return array Collection of material identifiers by navigation identifiers
187
     */
188
    protected function findByNavigationIDs($entityIDs = array())
189
    {
190
        return (new MaterialNavigation($entityIDs))->idsByRelationID(static::$navigationIDs);
191
    }
192
193
    /**
194
     * Get collection of entity identifiers filtered by additional field and its value.
195
     *
196
     * @param array $additionalFields Collection of additional field identifiers => values
197
     * @param array $entityIDs Additional collection of entity identifiers for filtering
198
     * @return array Collection of material identifiers by navigation identifiers
199
     */
200
    protected function findByAdditionalFields($additionalFields, $entityIDs = array())
201
    {
202
        /**
203
         * TODO: We have separate request to materialfield for each field, maybe faster to
204
         * make one single query with all fields conditions. Performance tests are needed.
205
         */
206
207
        // Iterate all additional fields needed for filter entity
208
        foreach ($additionalFields as $fieldID => $fieldValue) {
209
            // Get collection of entity identifiers passing already found identifiers
210
            $entityIDs = (new MaterialField($entityIDs))->idsByRelationID($fieldID, $fieldValue);
211
212
            // Stop execution if we have no entities found at this step
213
            if (!sizeof($entityIDs)) {
214
                break;
215
            }
216
        }
217
218
        return $entityIDs;
219
    }
220
221
    /**
222
     * Add sorting to entity identifiers.
223
     *
224
     * @param array $entityIDs
225
     * @param string $fieldName Additional field name for sorting
226
     * @param string $order Sorting order(ASC|DESC)
227
     * @return array Collection of entity identifiers ordered by additional field value
228
     */
229
    protected function applySorting(array $entityIDs, $fieldName, $order = 'ASC')
230
    {
231
        // Get additional field metadata
232
        $fieldID = static::$fieldNames[$fieldName];
233
        $valueColumn = static::$fieldValueColumns[$fieldID];
234
235
        return $this->query
236
            ->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY)
237
            ->where(Field::F_PRIMARY, $fieldID)
238
            ->where(Material::F_PRIMARY, $entityIDs)
239
            ->orderBy($valueColumn, $order)
240
            ->fields(Material::F_PRIMARY);
241
    }
242
243
    /**
244
     * Get entities additional field values.
245
     *
246
     * @param array $entityIDs Collection of entity identifiers
247
     * @return array Collection of entities additional fields EntityID => [Additional field name => Value]
248
     */
249
    protected function findAdditionalFields($entityIDs)
250
    {
251
        $return = array();
252
253
        // Copy fields arrays
254
        $localized = static::$localizedFieldIDs;
255
        $notLocalized = static::$notLocalizedFieldIDs;
256
257
        // If we filter additional fields that we need to receive
258
        if (sizeof($this->selectedFields)) {
259
            foreach ($this->selectedFields as $fieldID => $fieldName) {
260
                // Filter localized and not fields by selected fields
261
                if (!isset(static::$localizedFieldIDs[$fieldID])) {
262
                    unset($localized[$fieldID]);
263
                }
264
265
                if (!isset(static::$notLocalizedFieldIDs[$fieldID])) {
266
                    unset($notLocalized[$fieldID]);
267
                }
268
            }
269
        }
270
271
        // Prepare localized additional field query condition
272
        $condition = new Condition(Condition::DISJUNCTION);
273 View Code Duplication
        foreach ($localized as $fieldID => $fieldName) {
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...
274
            $condition->addCondition(
275
                (new Condition())
276
                    ->add(Field::F_PRIMARY, $fieldID)
277
                    ->add(Field::F_LOCALIZED, $this->locale)
278
            );
279
        }
280
281
        // Prepare not localized fields condition
282
        foreach ($notLocalized as $fieldID => $fieldName) {
283
            $condition->add(Field::F_PRIMARY, $fieldID);
284
        }
285
286
        // Get additional fields values for current entity identifiers
287
        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...
288
                     ->where(Material::F_PRIMARY, $entityIDs)
289
                     ->whereCondition($condition)
290
                     ->where(Material::F_DELETION, true)
291
                     ->exec() as $additionalField
292
        ) {
293
            // Get needed metadata
294
            $fieldID = $additionalField[Field::F_PRIMARY];
295
            $materialID = $additionalField[Material::F_PRIMARY];
296
            $valueField = static::$fieldValueColumns[$fieldID];
297
            $fieldName = static::$fieldIDs[$fieldID];
298
            $fieldValue = $additionalField[$valueField];
299
300
            // Gather additional fields values by entity identifiers and field name
301
            $return[$materialID][$fieldName] = $fieldValue;
302
        }
303
304
        return $return;
305
    }
306
307
    /**
308
     * Fill entity additional fields.
309
     *
310
     * @param Entity $entity Entity instance for filling
311
     * @param array $additionalFields Collection of additional field values
312
     * @return Entity With filled additional field values
313
     */
314
    protected function fillEntityFields($entity, array $additionalFields)
315
    {
316
        // If we have list of additional fields that we need
317
        $fieldIDs = sizeof($this->selectedFields) ? $this->selectedFields : static::$fieldIDs;
318
319
        // Iterate all entity additional fields
320
        foreach ($fieldIDs as $variable) {
321
            // Set only existing additional fields
322
            $pointer = &$additionalFields[$entity[Material::F_PRIMARY]][$variable];
323
            if (isset($pointer)) {
324
                $entity->$variable = $pointer;
325
            }
326
        }
327
328
        return $entity;
329
    }
330
331
    /**
332
     * Perform SamsonCMS query and get collection of entities.
333
     *
334
     * @return \samsoncms\api\Entity[] Collection of entity fields
335
     */
336
    public function find()
337
    {
338
        $return = array();
339
        if (sizeof($entityIDs = $this->findEntityIDs())) {
340
            $additionalFields = $this->findAdditionalFields($entityIDs);
341
342
            // Set entity primary keys
343
            $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...
344
345
            //elapsed('End fields values');
346
            /** @var \samsoncms\api\Entity $item Find entity instances */
347
            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...
348
                $item = $this->fillEntityFields($item, $additionalFields);
349
350
                // Store entity by identifier
351
                $return[$item[Material::F_PRIMARY]] = $item;
352
            }
353
        }
354
355
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
356
357
        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...
358
    }
359
360
    /**
361
     * Perform SamsonCMS query and get first matching entity.
362
     *
363
     * @return \samsoncms\api\Entity Firt matching entity
364
     */
365
    public function first()
366
    {
367
        $return = array();
368
        if (sizeof($entityIDs = $this->findEntityIDs())) {
369
            $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...
370
            $additionalFields = $this->findAdditionalFields($entityIDs);
371
            $return = $this->fillEntityFields(parent::first(), $additionalFields);
0 ignored issues
show
Documentation introduced by
parent::first() is of type object<samsonframework\orm\RecordInterface>|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...
372
        }
373
374
        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 samsonframework\orm\RecordInterface|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...
375
    }
376
377
    /**
378
     * Perform SamsonCMS query and get collection of entities fields.
379
     *
380
     * @param string $fieldName Entity field name
381
     * @return array Collection of entity fields
382
     * @throws EntityFieldNotFound
383
     */
384
    public function fields($fieldName)
385
    {
386
        $return = array();
387
        if (sizeof($entityIDs = $this->findEntityIDs())) {
388
            // Check if our entity has this field
389
            $fieldID = &static::$fieldNames[$fieldName];
390
            if (isset($fieldID)) {
391
                $return = $this->query
392
                    ->entity(\samsoncms\api\MaterialField::ENTITY)
393
                    ->where(Material::F_PRIMARY, $entityIDs)
394
                    ->where(Field::F_PRIMARY, $fieldID)
395
                    ->where(\samsoncms\api\MaterialField::F_DELETION, true)
396
                    ->fields(static::$fieldValueColumns[$fieldID]);
397
            } else {
398
                throw new EntityFieldNotFound($fieldName);
399
            }
400
        }
401
402
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
403
404
        return $return;
405
    }
406
407
    /**
408
     * Perform SamsonCMS query and get amount resulting entities.
409
     *
410
     * @return int Amount of resulting entities
411
     */
412
    public function count()
413
    {
414
        $return = 0;
415
        if (sizeof($entityIDs = $this->findEntityIDs())) {
416
            $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...
417
            $return = parent::count();
418
        }
419
420
        return $return;
421
    }
422
423
    /**
424
     * Generic constructor.
425
     *
426
     * @param QueryInterface $query Database query instance
427
     * @param string $locale Query localization
428
     */
429
    public function __construct(QueryInterface $query, $locale = NULL)
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
430
    {
431
        $this->locale = $locale;
432
433
        parent::__construct($query);
434
435
        // Work only with active entities
436
        $this->active(true);
437
    }
438
}
439