Completed
Push — master ( 53e43c...41b088 )
by Vitaly
03:02
created

Record::select()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 6

Duplication

Lines 14
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 14
loc 14
rs 9.2
cc 4
eloc 6
nc 3
nop 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: nazarenko
5
 * Date: 29.03.2016
6
 * Time: 10:52
7
 */
8
namespace samsoncms\api\query;
9
10
use samsonframework\orm\ArgumentInterface;
11
use samsonframework\orm\Condition;
12
use samsonframework\orm\ConditionInterface;
13
use samsonframework\orm\QueryInterface;
14
15
/**
16
 * Generic real database entity query class.
17
 *
18
 * @package samsoncms\api\query
19
 */
20
class Record
21
{
22
    /** @var string Table class name */
23
    protected static $identifier;
24
25
    /** @var string Table primary field name */
26
    protected static $primaryFieldName;
27
28
    /** @var array Collection of all entity fields */
29
    protected static $parentFields = array();
30
31
    /** @var QueryInterface Database query instance */
32
    protected $query;
33
34
    /** @var array Collection of entity fields to retrieved from database */
35
    protected $selectedFields;
36
37
    /** @var ConditionInterface Query conditions */
38
    protected $conditions;
39
40
    /** @var array Collection of ordering parameters */
41
    protected $orderBy = array();
42
43
    /** @var array Collection of limit parameters */
44
    protected $limit = array();
45
46
    /** @var array Collection of entity identifiers */
47
    protected $entityIDs = array();
48
49
    /**
50
     * Generic constructor.
51
     *
52
     * @param QueryInterface $query Database query instance
53
     */
54
    public function __construct(QueryInterface $query)
55
    {
56
        $this->query = $query;
57
        $this->conditions = new Condition();
58
    }
59
60
    /**
61
     * Select specified entity fields.
62
     * If this method is called then only selected entity fields
63
     * would be filled in entity instances.
64
     *
65
     * @param mixed $fieldNames Entity field name or collection of names
66
     *
67
     * @return $this Chaining
68
     */
69 View Code Duplication
    public function select($fieldNames)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
70
    {
71
        // Convert argument to array and iterate
72
        foreach ((!is_array($fieldNames) ? array($fieldNames) : $fieldNames) as $fieldName) {
73
            // Try to find entity additional field
74
            $pointer = &static::$fieldNames[$fieldName];
75
            if (null !== $pointer) {
76
                // Store selected additional field buy FieldID and Field name
77
                $this->selectedFields[$pointer] = $fieldName;
78
            }
79
        }
80
81
        return $this;
82
    }
83
84
    /**
85
     * Set field for sorting.
86
     *
87
     * @param string $fieldName Additional field name
88
     * @param string $order     Sorting order
89
     *
90
     * @return $this Chaining
91
     */
92 View Code Duplication
    public function orderBy($fieldName, $order = 'ASC')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
93
    {
94
        if (array_key_exists($fieldName, static::$parentFields)) {
95
            $this->orderBy = array($fieldName, $order);
96
        }
97
98
        return $this;
99
    }
100
101
    /**
102
     * Perform SamsonCMS query and get entities collection.
103
     *
104
     * @return \samsoncms\api\Entity[] Collection of found entities
105
     */
106 View Code Duplication
    public function find()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
107
    {
108
        $this->query->entity(static::$identifier);
109
110
        // Set entity primary keys if predefined
111
        if (count($this->entityIDs)) {
112
            $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...
113
        }
114
115
        // Add query sorter for showed page
116
        if (count($this->orderBy) === 2) {
117
            $this->query->orderBy($this->orderBy[0], $this->orderBy[1]);
118
        }
119
120
        // Proxy to regular database query
121
        $return = $this->query
122
            ->whereCondition($this->conditions)
123
            ->exec();
124
125
        // Reorder if entity identifiers collection was defined
126
        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 121 can also be of type boolean; however, samsoncms\api\query\Record::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...
127
    }
128
129
    /**
130
     * Add primary field query condition.
131
     *
132
     * @param string $value Field value
133
     *
134
*@return $this Chaining
135
     * @see Material::where()
136
     */
137
    public function primary($value)
138
    {
139
        return $this->where(static::$primaryFieldName, $value);
140
    }
141
142
    /**
143
     * Add condition to current query.
144
     *
145
     * @param string $fieldName  Entity field name
146
     * @param string $fieldValue Value
147
     * @param string $fieldRelation
148
     *
149
*@return $this Chaining
150
     */
151
    public function where($fieldName, $fieldValue = null, $fieldRelation = ArgumentInterface::EQUAL)
152
    {
153
        $this->conditions->add($fieldName, $fieldValue, $fieldRelation);
154
155
        return $this;
156
    }
157
158
    /**
159
     * Reorder elements in one array according to keys of another.
160
     *
161
     * @param array $array Source array
162
     * @param array $orderArray Ideal array
163
     * @return array Ordered array
164
     */
165 View Code Duplication
    protected function sortArrayByArray(array $array, array $orderArray)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
166
    {
167
        $ordered = array();
168
        foreach ($orderArray as $key) {
169
            if (array_key_exists($key, $array)) {
170
                $ordered[$key] = $array[$key];
171
                unset($array[$key]);
172
            }
173
        }
174
        return array_merge($ordered, $array);
175
    }
176
177
    /**
178
     * Perform SamsonCMS query and get collection of entities fields.
179
     *
180
     * @param string $fieldName Entity field name
181
     *
182
     * @return array Collection of entity fields
183
     */
184
    public function fields($fieldName)
185
    {
186
        // Proxy to regular database query
187
        return $this->query
188
            ->entity(static::$identifier)
189
            ->whereCondition($this->conditions)
190
            ->fields($fieldName);
191
    }
192
193
    /**
194
     * Perform SamsonCMS query and get first matching entity.
195
     *
196
     * @return \samsoncms\api\Entity First matching entity
197
     */
198 View Code Duplication
    public function first()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
199
    {
200
        // Proxy to regular database query
201
        $return = $this->query
202
            ->entity(static::$identifier)
203
            ->limit(1)
204
            ->whereCondition($this->conditions)
205
            ->exec();
206
207
        return array_shift($return);
208
    }
209
210
    /**
211
     * Perform SamsonCMS query and get amount resulting entities.
212
     *
213
     * @return int Amount of resulting entities
214
     */
215
    public function count()
216
    {
217
        // Proxy to regular database query
218
        return $this->query
219
            ->entity(static::$identifier)
220
            ->whereCondition($this->conditions)
221
            ->count();
222
    }
223
224
    /**
225
     * Convert date value to database format.
226
     * TODO: Must implement at database layer
227
     *
228
     * @param string $date Date value for conversion
229
     *
230
     * @return string Converted date to correct format
231
     */
232
    protected function convertToDateTime($date)
233
    {
234
        return date('Y-m-d H:i:s', strtotime($date));
235
    }
236
237
    /**
238
     * Add sorting to entity identifiers.
239
     *
240
     * @param array  $entityIDs
241
     * @param string $fieldName Additional field name for sorting
242
     * @param string $order     Sorting order(ASC|DESC)
243
     *
244
     * @return array Collection of entity identifiers ordered by additional field value
245
     */
246
    protected function applySorting(array $entityIDs, $fieldName, $order = 'ASC')
247
    {
248
        if (array_key_exists($fieldName, static::$parentFields)) {
249
            // Order by parent fields
250
            return $this->query
251
                ->entity(static::$identifier)
252
                ->where(static::$primaryFieldName, $entityIDs)
253
                ->orderBy($fieldName, $order)
254
                ->fields(static::$primaryFieldName);
255
        } else { // Nothing is changed
256
            return $entityIDs;
257
        }
258
    }
259
}
260