Passed
Push — master ( 89d796...1246a9 )
by Vitaly
29s
created

Generic::applySorting()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 13
rs 9.4285
cc 2
eloc 9
nc 2
nop 3
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: VITALYIEGOROV
5
 * Date: 08.12.15
6
 * Time: 23:11
7
 */
8
namespace samsoncms\api\query;
9
10
use samsoncms\api\Material;
11
use samsonframework\orm\ArgumentInterface;
12
use samsonframework\orm\Condition;
13
use samsonframework\orm\QueryInterface;
14
15
/**
16
 * Material with additional fields query.
17
 * @package samsoncms\api
18
 */
19
class Generic
20
{
21
    /** @var array Collection of all supported entity fields */
22
    protected static $parentFields = array(
23
        Material::F_PRIMARY=> Material::F_PRIMARY,
24
        Material::F_PRIORITY => Material::F_PRIORITY,
25
        Material::F_IDENTIFIER => Material::F_IDENTIFIER,
26
        Material::F_DELETION => Material::F_DELETION,
27
        Material::F_PUBLISHED => Material::F_PUBLISHED,
28
        Material::F_PARENT => Material::F_PARENT,
29
        Material::F_CREATED => Material::F_CREATED,
30
    );
31
32
    /** @var string Entity identifier */
33
    protected static $identifier;
34
35
    /** @var string Entity navigation identifiers */
36
    protected static $navigationIDs = array();
37
38
    /**
39
     * @var string Collection of entity field names
40
     * @deprecated Created for old application who need real additional field names
41
     */
42
    public static $fieldRealNames = array();
43
44
    /** @var string Collection of entity field names */
45
    public static $fieldNames = array();
46
47
48
    /** @var QueryInterface Database query instance */
49
    protected $query;
50
51
    /** @var array Collection of entity fields to retrieved from database */
52
    protected $selectedFields;
53
54
    /** @var Condition Query conditions */
55
    protected $conditions;
56
57
    /** @var array Collection of ordering parameters */
58
    protected $orderBy = array();
59
60
    /** @var array Collection of limit parameters */
61
    protected $limit = array();
62
63
    /** @var array Collection of entity identifiers */
64
    protected $entityIDs = array();
65
66
    /**
67
     * Convert date value to database format.
68
     * TODO: Must implement at database layer
69
     *
70
     * @param string $date Date value for conversion
71
     * @return string Converted date to correct format
72
     */
73
    protected function convertToDateTime($date)
74
    {
75
        return date("Y-m-d H:i:s", strtotime($date));
76
    }
77
78
    /**
79
     * Add sorting to entity identifiers.
80
     *
81
     * @param array $entityIDs
82
     * @param string $fieldName Additional field name for sorting
83
     * @param string $order Sorting order(ASC|DESC)
84
     * @return array Collection of entity identifiers ordered by additional field value
85
     */
86
    protected function applySorting(array $entityIDs, $fieldName, $order = 'ASC')
87
    {
88
       if (array_key_exists($fieldName, static::$parentFields)) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 7
Loading history...
89
            // Order by parent fields
90
            return $this->query
91
                ->entity(Material::class)
92
                ->where(Material::F_PRIMARY, $entityIDs)
93
                ->orderBy($fieldName, $order)
94
                ->fields(Material::F_PRIMARY);
95
        } else { // Nothing is changed
0 ignored issues
show
Coding Style introduced by
Closing brace indented incorrectly; expected 7 spaces, found 8
Loading history...
96
            return $entityIDs;
97
        }
98
    }
99
100
    /**
101
     * Add condition to current query.
102
     *
103
     * @param string $fieldName Entity field name
104
     * @param string $fieldValue Value
105
     * @return $this Chaining
106
     */
107
    public function where($fieldName, $fieldValue = null, $fieldRelation = ArgumentInterface::EQUAL)
108
    {
109
        $this->conditions->add($fieldName, $fieldValue, $fieldRelation);
110
111
        return $this;
112
    }
113
114
    /**
115
     * Set field for sorting.
116
     *
117
     * @param string $fieldName Additional field name
118
     * @param string $order Sorting order
119
     * @return $this Chaining
120
     */
121
    public function orderBy($fieldName, $order = 'ASC')
122
    {
123
        if (array_key_exists($fieldName, static::$parentFields)) {
124
            $this->orderBy = array($fieldName, $order);
125
        }
126
127
        return $this;
128
    }
129
130
    /**
131
     * Add primary field query condition.
132
     *
133
     * @param string $value Field value
134
     * @return $this Chaining
135
     * @see Material::where()
136
     */
137
    public function primary($value)
138
    {
139
        return $this->where(Material::F_PRIMARY, $value);
140
    }
141
142
    /**
143
     * Add identifier field query condition.
144
     *
145
     * @param string $value Field value
146
     * @return $this Chaining
147
     * @see Material::where()
148
     */
149
    public function identifier($value)
150
    {
151
        return $this->where(Material::F_IDENTIFIER, $value);
152
    }
153
154
    /**
155
     * Add active flag condition.
156
     *
157
     * @param bool $value Field value
158
     * @return $this Chaining
159
     * @see Material::where()
160
     */
161
    public function active($value)
162
    {
163
        return $this->where(Material::F_DELETION, $value);
0 ignored issues
show
Documentation introduced by
$value 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...
164
    }
165
166
    /**
167
     * Add entity published field query condition.
168
     *
169
     * @param string $value Field value
170
     * @return $this Chaining
171
     * @see Material::where()
172
     */
173
    public function published($value)
174
    {
175
        return $this->where(Material::F_PUBLISHED, $value);
176
    }
177
178
    /**
179
     * Add entity creation field query condition.
180
     *
181
     * @param string $value Field value
182
     * @param string $relation @see ArgumentInterface types
183
     * @return $this Chaining
184
     * @see Material::where()
185
     */
186
    public function created($value, $relation = ArgumentInterface::EQUAL)
187
    {
188
        return $this->where(Material::F_CREATED, $this->convertToDateTime($value), $relation);
189
    }
190
191
    /**
192
     * Add entity modification field query condition.
193
     *
194
     * @param string $value Field value
195
     * @param string $relation @see ArgumentInterface types
196
     * @return $this Chaining
197
     * @see Material::where()
198
     */
199
    public function modified($value, $relation = ArgumentInterface::EQUAL)
200
    {
201
        return $this->where(Material::F_MODIFIED, $this->convertToDateTime($value), $relation);
202
    }
203
204
    /**
205
     * Perform SamsonCMS query and get entities collection.
206
     *
207
     * @return \samsoncms\api\Entity[] Collection of found entities
208
     */
209
    public function find()
210
    {
211
        $this->query->entity(static::$identifier);
212
213
        // Set entity primary keys if predefined
214
        if (count($this->entityIDs)) {
215
            $this->primary($this->entityIDs);
0 ignored issues
show
Documentation introduced by
$this->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...
216
        }
217
218
        // Add query sorter for showed page
219
        if (count($this->orderBy) === 2) {
220
            $this->query->orderBy($this->orderBy[0], $this->orderBy[1]);
221
        }
222
223
        // Proxy to regular database query
224
        $return = $this->query
225
            ->whereCondition($this->conditions)
226
            ->exec();
227
228
        // Reorder if entity identifiers collection was defined
229
        return $this->sortArrayByArray($return, $this->entityIDs);
0 ignored issues
show
Bug introduced by
It seems like $return defined by $this->query->whereCondi...is->conditions)->exec() on line 224 can also be of type boolean; however, samsoncms\api\query\Generic::sortArrayByArray() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
230
    }
231
232
    /**
233
     * Reorder elements in one array according to keys of another.
234
     *
235
     * @param array $array Source array
236
     * @param array $orderArray Ideal array
237
     * @return array Ordered array
238
     */
239
    protected function sortArrayByArray(array $array, array $orderArray) {
240
        $ordered = array();
241
        foreach($orderArray as $key) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FOREACH keyword; 0 found
Loading history...
242
            if(array_key_exists($key,$array)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
243
                $ordered[$key] = $array[$key];
244
                unset($array[$key]);
245
            }
246
        }
247
        return $ordered + $array;
248
    }
249
250
    /**
251
     * Perform SamsonCMS query and get collection of entities fields.
252
     *
253
     * @param string $fieldName Entity field name
254
     * @return array Collection of entity fields
255
     */
256
    public function fields($fieldName)
257
    {
258
        // Proxy to regular database query
259
        return $this->query
260
            ->entity(static::$identifier)
261
            ->whereCondition($this->conditions)
262
            ->fields($fieldName);
263
    }
264
265
    /**
266
     * Perform SamsonCMS query and get first matching entity.
267
     *
268
     * @return \samsoncms\api\Entity First matching entity
269
     */
270
    public function first()
271
    {
272
        // Proxy to regular database query
273
        $return = $this->query
274
            ->entity(static::$identifier)
275
            ->limit(1)
276
            ->whereCondition($this->conditions)
277
            ->exec();
278
279
        return array_shift($return);
280
    }
281
282
    /**
283
     * Perform SamsonCMS query and get amount resulting entities.
284
     *
285
     * @return int Amount of resulting entities
286
     */
287
    public function count()
288
    {
289
        // Proxy to regular database query
290
        return $this->query
291
            ->entity(static::$identifier)
292
            ->whereCondition($this->conditions)
293
            ->count();
294
    }
295
296
    /**
297
     * Generic constructor.
298
     *
299
     * @param QueryInterface $query Database query instance
300
     */
301
    public function __construct(QueryInterface $query)
302
    {
303
        $this->query = $query;
304
        $this->conditions = new Condition();
305
    }
306
}
307