Query::flush()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 8
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 11
rs 9.4285
1
<?php declare(strict_types=1);
2
namespace samsonframework\orm;
3
4
use samson\activerecord\dbQuery;
5
use samsonframework\container\definition\analyzer\annotation\annotation\Service;
6
7
/**
8
 * Database query builder.
9
 *
10
 * @author Vitaly Iegorov <[email protected]>
11
 * @Service("query")
12
 */
13
class Query extends dbQuery implements QueryInterface
0 ignored issues
show
Deprecated Code introduced by
The class samson\activerecord\dbQuery has been deprecated with message: Should be removed ASAP in favor of generated classes or DI

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
14
{
15
    /** @var TableMetadata */
16
    protected $metadata;
17
18
    /** @var array Collection of parent table selected fields */
19
    protected $select = [];
20
21
    /** @var array Collection of entity field names for sorting order */
22
    protected $sorting = [];
23
24
    /** @var array Collection of entity field names for grouping query results */
25
    protected $grouping = [];
26
27
    /** @var array Collection of query results limitations */
28
    protected $limitation = [];
29
30
    /** @var TableMetadata[] Collection of joined entities */
31
    protected $joins = [];
32
33
    /** @var Condition Query entity condition group */
34
    protected $condition;
35
36
    /** @var DatabaseInterface Database instance */
37
    protected $database;
38
39
    /** @var SQLBuilder SQL builder */
40
    protected $sqlBuilder;
41
42
    /**
43
     * Query constructor.
44
     *
45
     * @param               Database Database instance
46
     * @param SQLBuilder    $sqlBuilder
47
     */
48
    public function __construct(Database $database, SQLBuilder $sqlBuilder)
49
    {
50
        $this->database = $database;
51
        $this->sqlBuilder = $sqlBuilder;
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57
    public function find() : array
58
    {
59
        return $this->database->fetchObjects($this->buildSQL(), $this->metadata);
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65
    public function flush() : QueryInterface
66
    {
67
        $this->select = [];
68
        $this->sorting = [];
69
        $this->grouping = [];
70
        $this->limitation = [];
71
        $this->joins = [];
72
        $this->condition = new Condition();
73
74
        return $this;
75
    }
76
77
    /**
78
     * Build SQL statement from this query.
79
     *
80
     * @return string SQL statement
81
     * @throws \InvalidArgumentException
82
     */
83
    protected function buildSQL() : string
84
    {
85
        // If none fields are selected - select all fields from parent table
86
        $this->select = count($this->select) ? $this->select : [$this->metadata->tableName => '*'];
87
88
        $sql = $this->sqlBuilder->buildSelectStatement($this->select);
89
        $sql .= "\n" . $this->sqlBuilder->buildFromStatement(
90
                array_merge(array_keys($this->select), array_keys($this->joins))
91
            );
92
93
        $whereCondition = $this->sqlBuilder->buildWhereStatement($this->metadata, $this->condition);
94
95
        if (isset($whereCondition{0})) {
96
            $sql .= "\n" . 'WHERE ' . $whereCondition;
97
        }
98
99
        if (count($this->grouping)) {
100
            $sql .= "\n" . $this->sqlBuilder->buildGroupStatement($this->grouping);
101
        }
102
103
        if (count($this->sorting)) {
104
            $sql .= "\n" . $this->sqlBuilder->buildOrderStatement($this->sorting[0], $this->sorting[1]);
105
        }
106
107
        if (count($this->limitation)) {
108
            $sql .= "\n" . $this->sqlBuilder->buildLimitStatement($this->limitation[0], $this->limitation[1]);
109
        }
110
111
        return $sql;
112
    }
113
114
    /**
115
     * {@inheritdoc}
116
     */
117
    public function count() : int
118
    {
119
        return $this->database->count($this->buildSQL());
120
    }
121
122
    /**
123
     * {@inheritdoc}
124
     */
125
    public function first()
126
    {
127
        $return = $this->limit(1)->exec();
0 ignored issues
show
Deprecated Code introduced by
The method samson\activerecord\dbQuery::exec() has been deprecated with message: Use self::find()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
128
129
        return count($return) ? array_shift($return) : null;
0 ignored issues
show
Bug Compatibility introduced by
The expression count($return) ? array_shift($return) : null; of type samson\activerecord\RecordInterface|null adds the type samson\activerecord\RecordInterface to the return on line 129 which is incompatible with the return type declared by the interface samsonframework\orm\QueryInterface::first of type boolean|samsonframework\orm\RecordInterface.
Loading history...
130
    }
131
132
    /**
133
     * {@inheritdoc}
134
     */
135
    public function limit(int $quantity, int $offset = 0) : QueryInterface
136
    {
137
        $this->limitation = [$quantity, $offset];
138
139
        // Chaining
140
        return $this;
141
    }
142
143
    /**
144
     * {@inheritdoc}
145
     */
146
    public function fields(string $fieldName) : array
147
    {
148
        // Return bool or collection
149
        return $this->database->fetchColumn($this->buildSQL(), $this->metadata->getTableColumnIndex($fieldName));
150
    }
151
152
    /**
153
     * {@inheritdoc}
154
     */
155
    public function entity($metadata) : QueryInterface
156
    {
157
        if (is_string($metadata)) {
158
            // Remove old namespace
159
            $metadata = strpos($metadata, '\samson\activerecord\\') !== false ? str_replace('\samson\activerecord\\', '', $metadata) : $metadata;
160
            $metadata = strpos($metadata, 'samson\activerecord\\') !== false ? str_replace('samson\activerecord\\', '', $metadata) : $metadata;
161
            // Capitalize and add cms namespace
162
            $metadata = strpos($metadata, '\\') === false ? 'samsoncms\api\generated\\' . ucfirst($metadata) : $metadata;
163
164
            $this->metadata = TableMetadata::fromClassName($metadata);
0 ignored issues
show
Deprecated Code introduced by
The method samsonframework\orm\TableMetadata::fromClassName() has been deprecated with message: This is temporary old approach

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
165
        } else {
166
            $this->metadata = $metadata;
167
        }
168
169
        $this->flush();
170
171
        return $this;
172
    }
173
174
    /**
175
     * {@inheritdoc}
176
     */
177
    public function orderBy(string $fieldName, string $order = 'ASC', string $tableName = null) : QueryInterface
178
    {
179
        $this->sorting[0][$tableName ?? $this->metadata->tableName][] = $fieldName;
180
        $this->sorting[1][] = $order;
181
182
        // Chaining
183
        return $this;
184
    }
185
186
    /**
187
     * {@inheritdoc}
188
     */
189
    public function whereCondition(ConditionInterface $condition) : QueryInterface
190
    {
191
        $this->condition->addCondition($condition);
192
193
        return $this;
194
    }
195
196
    /**
197
     * {@inheritdoc}
198
     */
199
    public function select(string $tableName, string $fieldName) : QueryInterface
200
    {
201
        $this->select[$tableName][] = $fieldName;
202
203
        return $this;
204
    }
205
206
    /**
207
     * {@inheritdoc}
208
     */
209
    public function join(string $entityName) : QueryInterface
210
    {
211
        $this->joins[$entityName] = [];
212
213
        // Chaining
214
        return $this;
215
    }
216
217
    /**
218
     * {@inheritdoc}
219
     */
220
    public function groupBy(string $tableName, string $fieldName) : QueryInterface
221
    {
222
        $this->grouping[$tableName][] = $fieldName;
223
224
        // Chaining
225
        return $this;
226
    }
227
228
    /**
229
     * {@inheritdoc}
230
     */
231
    public function isNull(string $fieldName) : QueryInterface
232
    {
233
        return $this->where($fieldName, '', ArgumentInterface::ISNULL);
234
    }
235
236
    /**
237
     * {@inheritdoc}
238
     */
239
    public function where(
240
        string $fieldName,
241
        $fieldValue = null,
242
        string $relation = ArgumentInterface::EQUAL
243
    ) : QueryInterface
244
    {
0 ignored issues
show
Coding Style introduced by
The closing parenthesis and the opening brace of a multi-line function declaration must be on the same line
Loading history...
245
        // Add condition argument
246
        $this->condition->add($fieldName, $fieldValue, $relation);
247
248
        return $this;
249
    }
250
251
    /**
252
     * {@inheritdoc}
253
     */
254
    public function notNull(string $fieldName) : QueryInterface
255
    {
256
        return $this->where($fieldName, '', ArgumentInterface::NOTNULL);
257
    }
258
259
    /**
260
     * {@inheritdoc}
261
     */
262
    public function notEmpty(string $fieldName) : QueryInterface
263
    {
264
        return $this->where($fieldName, '', ArgumentInterface::NOT_EQUAL);
265
    }
266
267
    /**
268
     * {@inheritdoc}
269
     */
270
    public function like(string $fieldName, string $value = '') : QueryInterface
271
    {
272
        return $this->where($fieldName, $value, ArgumentInterface::LIKE);
273
    }
274
275
    /**
276
     * {@inheritdoc}
277
     */
278
    public function primary($value) : QueryInterface
279
    {
280
        return $this->where($this->metadata->primaryField, $value);
281
    }
282
}
283