Completed
Push — master ( ad8ffb...6a6774 )
by Vitaly
14:22 queued 11:33
created

Entity::fields()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 22
rs 9.2
cc 3
eloc 14
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 samsoncms\api\exception\EntityFieldNotFound;
11
use samsoncms\api\Field;
12
use samsoncms\api\Material;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, samsoncms\api\query\Material.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
13
use samsonframework\orm\ArgumentInterface;
14
use samsonframework\orm\Condition;
15
use samsonframework\orm\QueryInterface;
16
17
/**
18
 * Generic SamsonCMS Entity query.
19
 * @package samsoncms\api\query
20
 */
21
class Entity extends Material
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;
0 ignored issues
show
Bug introduced by
The property selectedFields does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
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);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class samsoncms\api\Material as the method where() does only exist in the following sub-classes of samsoncms\api\Material: samsoncms\api\query\Entity. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
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
Coding Style introduced by
Space found before closing bracket of FOREACH loop
Loading history...
Bug introduced by
The property query does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
182
                     ->where(Material::F_PRIMARY, $entityIDs)
183
                     ->whereCondition($condition)
184
                     ->where(Material::F_DELETION, true)
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);
0 ignored issues
show
Bug introduced by
The method primary() does not seem to exist on object<samsoncms\api\query\Entity>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
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
It seems like you code against a specific sub-type and not the parent class samsoncms\api\Material as the method find() does only exist in the following sub-classes of samsoncms\api\Material: samsoncms\api\query\Entity. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
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;
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();
247
        if (sizeof($entityIDs = $this->findEntityIDs())) {
248
            $this->primary($entityIDs);
0 ignored issues
show
Bug introduced by
The method primary() does not seem to exist on object<samsoncms\api\query\Entity>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
249
250
            $return = parent::first();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class samsoncms\api\Material as the method first() does only exist in the following sub-classes of samsoncms\api\Material: samsoncms\api\query\Entity. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
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();
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(\samsoncms\api\MaterialField::ENTITY)
272
                    ->where(Material::F_PRIMARY, $entityIDs)
273
                    ->where(Field::F_PRIMARY, $fieldID)
274
                    ->where(\samsoncms\api\MaterialField::F_DELETION, true)
275
                    ->fields(static::$fieldValueColumns[$fieldID]);
276
            } else {
277
                throw new EntityFieldNotFound($fieldName);
278
            }
279
        }
280
281
        //elapsed('Finish SamsonCMS '.static::$identifier.' query');
282
283
        return $return;
284
    }
285
286
    /**
287
     * Generic constructor.
288
     *
289
     * @param QueryInterface $query Database query instance
290
     * @param string $locale Query localizaation
291
     */
292
    public function __construct(QueryInterface $query, $locale = '')
293
    {
294
        $this->locale = $locale;
295
296
        parent::__construct($query);
297
    }
298
}
299