Completed
Push — master ( 9bac79...ed2dfa )
by Vitaly
04:34
created

dbQuery::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 2
Metric Value
c 4
b 0
f 2
dl 0
loc 5
rs 9.4286
cc 1
eloc 3
nc 1
nop 1
1
<?php 
2
namespace samson\activerecord;
3
4
//TODO: Написать метод ALL()
5
//TODO: Поддержка нескольких подключений
6
/**
7
 * Запрос для БД
8
 * Класс собирает в себя все необходимые параметры для 
9
 * формирования "правильного" запроса на самом низком уровне
10
 * работы с БД
11
 * @author Vitaly Iegorov <[email protected]> 
12
 *
13
 */
14
class dbQuery extends \samsonframework\orm\Query
0 ignored issues
show
Coding Style introduced by
This class is not in CamelCase format.

Classes in PHP are usually named in CamelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. The whole name starts with a capital letter as well.

Thus the name database provider becomes DatabaseProvider.

Loading history...
15
{
16
    /**
17
     * Указатель на текущую группу условий с которой работает запрос
18
     *
19
     * @var Condition
20
     */
21
    public $cConditionGroup;
22
23
    /**
24
     * Указатель на соединение с БД
25
     * @var resource
26
     */
27
    public $link;
28
29
    /**
30
     * Указатель на группу условий для текущего объекта с которой работает запрос
31
     *
32
     * @var Condition
33
     */
34
    public $own_condition;
35
36
    /** Limiting filter for base table */
37
    public $own_limit;
38
39
    /** Grouping filter for base table */
40
    public $own_group;
41
42
    /** Sorting filter for base table */
43
    public $own_order;
44
45
    /** Virtual field for base table */
46
    public $own_virtual_fields = array();
47
48
    /** Virtual fields */
49
    public $virtual_fields = array();
50
51
    public $empty = false;
52
53
    /** @var bool True to show requests */
54
    protected $debug = false;
55
56
    /**
57
     * Коллекция условных групп для запроса
58
     * @var dbConditionGroup
59
     */
60
    public $condition;
61
62
    /**
63
     * Параметры ограничения результатов запроса к БД
64
     * @var array
65
     */
66
    public $limit  = array();
67
68
    /**
69
     * Параметры сортировки результатов запроса к БД
70
     * @var array
71
     */
72
    public $order  = array();
73
74
    /**
75
     * Параметры группировки результатов запроса к БД
76
     * @var array
77
     */
78
    public $group  = array();
79
80
    /**
81
     * Коллекция параметров для запроса к связанным объектам
82
     * @var array
83
     */
84
    public $join = array();
85
86
87
88
    /** Query handlers stack */
89
    protected $stack = array();
90
91
    /** Query parameters stack */
92
    protected $params = array();
93
94
// 	/**
95
// 	 * Universal handler to pass to CMSMaterial::get()	 *
96
// 	 * @param samson\activerecord\dbQuery $db_query Original db query object for modifiyng
97
// 	 *
98
// 	 */
99
// 	protected function __handler()
100
// 	{
101
// 		// Iterate handlers and run them
102
// 		foreach ( $this->stack as $i => $handler )
103
// 		{
104
// 			// Create handler params array with first parameter pointing to this query object			
105
// 			$params = array( &$this );		
106
107
// 			// Combine params with existing ones in one array
108
// 			$params = array_merge( $params, $this->params[ $i ] ); 			
109
110
// 			// Append this query object as first handler parameter
111
// 			//array_unshift( $this->params[ $i ] , & $this );			
112
113
// 			//trace($this->params[ $i ]);
114
// 			call_user_func_array( $handler, $params );
115
// 		}
116
// 	}
117
118
// 	/**
119
// 	 * Add query handler
120
// 	 * @param callable $callable External handler
121
// 	 * @return samson\activerecord\dbQuery
122
// 	 */
123
// 	public function handler( $callable )
124
// 	{
125
// 		// If normal handler is passed
126
// 		if( is_callable( $callable ) )
127
// 		{
128
// 			// Add handler
129
// 			$this->stack[] = $callable;
130
131
// 			// Get passed arguments
132
// 			$args = func_get_args();
133
134
// 			// Remove first argument
135
// 			array_shift( $args );
136
137
// 			// Add handler parameters stack
138
// 			$this->params[] = & $args;
139
// 		}
140
// 		else e('Cannot set CMS Query handler - function(##) does not exists', E_SAMSON_CMS_ERROR, $callable );
141
142
// 		return $this;
143
// 	}
144
145
    // 	/** @see idbQuery::fields() */
146
    // 	public function fields( $field_name, & $return_value = null )
147
    // 	{
148
    // 		// Call handlers stack
149
    // 		$this->_callHandlers();
150
151
    // 		// Iterate records and gather specified field
152
    // 		$return_value = array();
153
    // 		foreach ( db()->find( $this->class_name, $this ) as $record ) $return_value[] =  $record->$field_name;
154
155
    // 		// Clear this query
156
    // 		$this->flush();
157
158
    // 		// Method return value
159
    // 		$return = null;
160
161
    // 		// If return value is passed - return boolean about request results
162
    // 		if( func_num_args() > 1 ) $return = (is_array( $return_value ) && sizeof( $return_value ));
163
    // 		// Set request results as return value
164
    // 		else $return = & $return_value;
165
166
    // 		// Otherwise just return request results
167
    // 		return $return;
168
    // 	}
169
170
    // 	/** @see idbQuery::get() */
171
    // 	public function & exec( & $return_value = null)
172
    // 	{
173
    // 		// Call handlers stack
174
    // 		$this->_callHandlers();
175
176
    // 		// Perform DB request
177
    // 		$return_value = db()->find( $this->class_name, $this );
178
179
    // 		// Clear this query
180
    // 		$this->flush();
181
182
    // 		// Method return value
183
    // 		$return = null;
184
185
    // 		// If return value is passed - return boolean about request results
186
    // 		if( func_num_args() ) $return = (is_array( $return_value ) && sizeof( $return_value ));
187
    // 		// Set request results as return value
188
    // 		else $return = & $return_value;
189
190
    // 		// Otherwise just return request results
191
    // 		return $return;
192
    // 	}
193
194
    // 	/** @see idbQuery::first() */
195
    // 	public function & first( & $return_value = null)
196
    // 	{
197
    // 		// Call handlers stack
198
    // 		$this->_callHandlers();
199
200
    // 		// Выполним запрос к БД
201
    // 		$return_value = db()->find( $this->class_name, $this );
202
203
    // 		// Получим первую запись из полученного массива, если она есть
204
    // 		$return_value = isset( $return_value[0] ) ? $return_value[0] : null;
205
206
    // 		// Очистим запрос
207
    // 		$this->flush();
208
209
    // 		// Локальная переменная для возврата правильного результата
210
    // 		$return = null;
211
212
    // 		// Если хоть что-то передано в функцию - запишем в локальную переменную boolean значение
213
    // 		// которое покажет результат выполнения запроса к БД
214
    // 		if( func_num_args() ) $return = isset( $return_value );
215
    // 		// Сделаем копию полученных данных в локальную переменную
216
    // 		else $return = & $return_value;
217
218
    // 		// Вернем значение из локальной переменной
219
    // 		return $return;
220
    // 	}
221
222
    /** */
223
    public function own_limit($st, $en = NULL)
0 ignored issues
show
Coding Style introduced by
Method name "dbQuery::own_limit" is not in camel caps format
Loading history...
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
224
    {
225
        $this->own_limit = array($st, $en);
226
        return $this;
227
    }
228
229
    /** */
230
    public function own_group_by($params)
0 ignored issues
show
Coding Style introduced by
Method name "dbQuery::own_group_by" is not in camel caps format
Loading history...
231
    {
232
        $this->own_group[] = $params;
233
        return $this;
234
    }
235
236
    /** */
237
    public function own_order_by($field, $direction = 'ASC')
0 ignored issues
show
Coding Style introduced by
Method name "dbQuery::own_order_by" is not in camel caps format
Loading history...
238
    {
239
        $this->own_order = array($field,$direction);
240
        return $this;
241
    }
242
243
    /** @see idbQuery::flush() */
244
    public function flush()
245
    {
246
        // Очистим параметры запроса
247
        $this->condition = new Condition();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \samson\activerecord\Condition() of type object<samson\activerecord\Condition> is incompatible with the declared type object<samson\activerecord\dbConditionGroup> of property $condition.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
Deprecated Code introduced by
The class samson\activerecord\Condition has been deprecated with message: use \samsonframework\orm\Condition

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...
248
        $this->limit = array();
249
        $this->order = array();
250
        $this->group = array();
251
        $this->join = array();
252
253
        $this->own_condition = new Condition();
0 ignored issues
show
Deprecated Code introduced by
The class samson\activerecord\Condition has been deprecated with message: use \samsonframework\orm\Condition

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...
254
        $this->own_group = array();
255
        $this->own_virtual_fields = array();
256
        $this->own_limit = array();
257
        $this->own_order = array();
258
259
        $this->cConditionGroup = &$this->condition;
260
    }
261
262
    /** @see idbQuery::random() */
263
    public function random(& $return_value = null)
264
    {
265
        // Add random ordering
266
        $this->order_by('', 'RAND()');
267
268
        // Correctly perform db request for multiple data
269
        return func_num_args() ? $this->exec($return_value) : $this->exec();
270
    }
271
272
273
    /**
274
     * @see idbQuery::or_()
275
     * @deprecated
276
     */
277
    public function or_($relation = 'OR')
0 ignored issues
show
Coding Style introduced by
Method name "dbQuery::or_" is not in camel caps format
Loading history...
278
    {
279
        // Получим либо переданную группу условий, либо создадим новую, потом добавим её в массив групп условий запроса
280
        $cond_group = new Condition($relation);
0 ignored issues
show
Deprecated Code introduced by
The class samson\activerecord\Condition has been deprecated with message: use \samsonframework\orm\Condition

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...
281
282
        // Установим текущую группу условий с которой работает запрос
283
        $this->cConditionGroup = &$cond_group;
284
285
        // Добавим нову группу условий в коллекцию групп
286
        $this->condition->arguments[] = $cond_group;
287
288
        // Вернем себя для цепирования
289
        return $this;
290
    }
291
292
    /**
293
     * Set debug query mode
294
     * @param bool $value Debug status, true - active
295
     *
296
     * @return $this Chaining
297
     */
298
    public function debug($value = true)
299
    {
300
        db()->debug($this->debug = $value);
301
302
        return $this;
303
    }
304
305
    public function isnull($attribute)
306
    {
307
        return $this->cond($attribute, '', dbRelation::ISNULL);
0 ignored issues
show
Documentation Bug introduced by
The method cond does not exist on object<samson\activerecord\dbQuery>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
308
    }
309
    public function notnull($attribute)
310
    {
311
        return $this->cond($attribute, '', dbRelation::NOTNULL);
0 ignored issues
show
Documentation Bug introduced by
The method cond does not exist on object<samson\activerecord\dbQuery>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
312
    }
313
    public function notempty($attribute)
314
    {
315
        return $this->cond($attribute, '', dbRelation::NOT_EQUAL);
0 ignored issues
show
Documentation Bug introduced by
The method cond does not exist on object<samson\activerecord\dbQuery>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
316
    }
317
    public function like($attribute, $value = '')
318
    {
319
        return $this->cond($attribute, $value, dbRelation::LIKE);
0 ignored issues
show
Documentation Bug introduced by
The method cond does not exist on object<samson\activerecord\dbQuery>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
320
    }
321
322
323
324
    /** @deprecated Use self::fields() */
325
    public function fieldsNew($fieldName, & $return = null)
0 ignored issues
show
Unused Code introduced by
The parameter $fieldName 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...
Unused Code introduced by
The parameter $return 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...
326
    {
327
        return call_user_func_array(array($this, 'fields'), func_get_args());
328
    }
329
330
    /** @see idbQuery::join() */
331
    public function join($tableName, $className = null, $ignore = false)
332
    {
333
        // Добавим имя класса в коллекцию присоединения
334
        $this->join[] = new RelationData($this->class_name, $tableName, $className, $ignore);
335
336
        // Вернем себя для цепирования
337
        return $this;
338
    }
339
340
    /** @see idbQuery::group_by() */
341
    public function group_by($field)
0 ignored issues
show
Coding Style introduced by
Method name "dbQuery::group_by" is not in camel caps format
Loading history...
342
    {
343
        // Default grouping array
344
        $destination = &$this->group;
345
346
        // If this field belongs to query main class
347
        //if (property_exists( $this->class_name, $field )) $destination = & $this->own_group;
348
349
        $destination[] = $field;
350
351
        // Вернем себя для цепирования
352
        return $this;
353
    }
354
355
    /** @see idbQuery::limit() */
356
    public function limit($st, $en = NULL, $own = false)
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
357
    {
358
        // Select base table or whole query destination
359
        if ($own) {
360
            $this->own_limit = array($st, $en);
361
        } else {
362
            $this->limit = array($st, $en);
363
        }
364
365
        // Вернем себя для цепирования
366
        return $this;
367
    }
368
369
    /** @see idbQuery::order_by() */
370
    public function order_by($field, $direction = 'ASC')
0 ignored issues
show
Coding Style introduced by
Method name "dbQuery::order_by" is not in camel caps format
Loading history...
371
    {
372
        $this->order[] = array($field, $direction);
373
374
        // Вернем себя для цепирования
375
        return $this;
376
    }
377
378
    /** @see idbQuery::add_field() */
379
    public function add_field($field, $alias = null, $own = true)
0 ignored issues
show
Coding Style introduced by
Method name "dbQuery::add_field" is not in camel caps format
Loading history...
380
    {
381
        // Если передан псевдоним для поля, то подставим его
382
        if (isset($alias)) {
383
            $field = $field . ' as ' . $alias;
384
        } else {
385
            $alias = $field;
386
        }
387
388
        // Добавим виртуальное поле
389
        if ($own) {
390
            $this->own_virtual_fields[$alias] = $field;
391
        } else {
392
            $this->virtual_fields[$alias] = $field;
393
        }
394
395
        // Вернем себя для цепирования
396
        return $this;
397
    }
398
399
    /** @see idbQuery::count() */
400
    public function count($field = '*')
0 ignored issues
show
Unused Code introduced by
The parameter $field 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...
401
    {
402
        return db()->count($this->class_name, $this);
403
    }
404
405
    /** @see idbQuery::innerCount() */
406
    public function innerCount($field = '*')
0 ignored issues
show
Unused Code introduced by
The parameter $field 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...
407
    {
408
        return db()->innerCount($this->class_name, $this);
409
    }
410
411
    /**	@see idbQuery::parse() */
0 ignored issues
show
Coding Style introduced by
Spaces must be used for alignment; tabs are not allowed
Loading history...
412
    public function parse($queryText, array $args = null)
413
    {
414
        // Преобразуем текст в нижний регистр
415
        //$query_text = mb_strtolower( $query_text, 'UTF-8' );
416
417
        // Паттерн для определения метода динамического запроса
418
        $sortingPattern = '
419
		/(?:^(?<method>find_by|find_all_by|all|first|last)_)
420
			|_order_by_  (?P<order>[a-zа-я0-9]+) _ (?P<order_dir>(?:asc|desc))
421
			|_limit_ (?P<limit_start>\d+) (?:_(?P<limit_end>\d+))?
422
			|_group_by_(?P<group>.+)
423
			|_join_ (?<join>.+)
424
		/iux';
425
426
        // Это внутренний счетчик для аргументов запроса для того чтобы не сбиться при их подставлении
427
        // в условие запроса к БД
428
        $argsCnt = 0;
429
430
        // Выполним первоначальный парсинг проверяющий правильность указанного метода
431
        // выборки данных и поиск возможных модификаторов запроса
432
        if (preg_match_all($sortingPattern, $queryText, $globalMatches)) {
433
            // Удалим все пустые группы полученные послке разпознования
434
            $globalMatches = array_filter_recursive($globalMatches);
435
436
            // Получим текст условий самого запроса, убрав из него все возможные модификаторы и параметры
437
            // и переберем только полученные группы условий запроса
438
            foreach (explode('_or_', str_ireplace($globalMatches[0], '', $queryText)) as $groupText) {
439
                // Добавим группу условий к запросу
440
                $this->or_('AND');
0 ignored issues
show
Deprecated Code introduced by
The method samson\activerecord\dbQuery::or_() has been deprecated.

This method has been deprecated.

Loading history...
441
442
                // Переберем поля которые формируют условия запроса - создание объекты-условия запроса
443
                foreach (explode('_and_', $groupText) as $conditionText) {
444
                    $this->cond($conditionText, $args[$argsCnt++]);
0 ignored issues
show
Documentation Bug introduced by
The method cond does not exist on object<samson\activerecord\dbQuery>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
445
                }
446
            }
447
448
            // Получим сортировку запроса
449
            if (isset($globalMatches['order'])) {
450
                $this->order = array($globalMatches['order'][0], $globalMatches['order_dir'][0]);
451
            }
452
            // Получим ограничения запроса
453
            if (isset($globalMatches['limit_start'])) {
454
                $this->limit = array($globalMatches['limit_start'][0], $globalMatches['limit_end'][0]);
455
            }
456
            // Получим групировку запроса
457 View Code Duplication
            if (isset($globalMatches['group'])) {
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...
458
                $this->group = explode('_and_', $globalMatches['group'][0]);
459
            }
460
            // Получим имена таблиц для "объединения" в запросе
461 View Code Duplication
            if (isset($globalMatches['join'])) {
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...
462
                foreach (explode('_and_', $globalMatches['join'][0]) as $join) {
463
                    $this->join($join);
464
                }
465
            }
466
        }
467
468
        // Вернем полученный объект-запрос
469
        return $this;
470
    }
471
472
    /**
473
     * Function to reconfigure dbQuery to work with multiple Entities
474
     *
475
     * @param string $className Entity name
476
     * @deprecated @see \samsonframework\orm\QueryInterface::entity(), full class name with namespace
477
     *                 should be passed.
478
     * @return self|string Chaining or current class name if nothing is passed
479
     */
480
    public function className($className = null)
481
    {
482
        // Old support for not full class names
483
        if (strpos($className, '\\') === false) {
484
            // Add generic namespace
485
            $className = '\samson\activerecord\\'.$className;
486
        }
487
488
        return func_num_args() > 0 ? $this->entity($className) : $this->entity();
0 ignored issues
show
Documentation Bug introduced by
The method entity does not exist on object<samson\activerecord\dbQuery>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
489
    }
490
491
    /**
492
     * Query constructor.
493
     * @param string|null $entity Entity identifier
494
     * @throws EntityNotFound
495
     */
496
    public function __construct($entity = null)
497
    {
498
        $this->className($entity);
0 ignored issues
show
Deprecated Code introduced by
The method samson\activerecord\dbQuery::className() has been deprecated with message: @see \samsonframework\orm\QueryInterface::entity(), full class name with namespace should be passed.

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...
499
        $this->flush();
500
    }
501
502
    // Magic method after-clonning
503
    public function __clone()
504
    {
505
        // Remove old references
506
        $condition = $this->condition;
507
        unset($this->condition);
508
509
        // Set new one on copied values
510
        $this->condition = $condition;
511
        $this->cConditionGroup = &$this->condition;
512
    }
513
514
    // Магический метод для выполнения не описанных динамических методов класса
515
    public function __call($methodName, array $arguments)
516
    {
517
        /** @var array $matches Prepared statement matches */
518
        $matches = array();
519
        // Если этот метод поддерживается - выполним запрос к БД
520
        if (preg_match('/^(find_by|find_all_by|all)/iu', $methodName, $matches)) {
521
            return db()->find($this->class_name, $this->parse($methodName, $arguments));
522
        } elseif (property_exists($this->class_name, $methodName)) { // Проверим существует ли у класса заданное поле
523
524
            // Если передан аргумент - расцениваем его как аргумент запроса
525
            if (sizeof($arguments) > 1) {
526
                return $this->cond($methodName, $arguments[0], $arguments[1]);
0 ignored issues
show
Documentation Bug introduced by
The method cond does not exist on object<samson\activerecord\dbQuery>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
527
            } elseif (isset($arguments[0])) {
528
                return $this->cond($methodName, $arguments[0]);
0 ignored issues
show
Documentation Bug introduced by
The method cond does not exist on object<samson\activerecord\dbQuery>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
529
            } else { // Просто игнорируем условие
530
                return $this;
531
            }
532
        } else { // Сообщим об ошибке разпознования метода
533
            return e(
534
                'Не возможно определить метод(##) для создания запроса к БД',
535
                E_SAMSON_ACTIVERECORD_ERROR,
536
                $methodName
537
            );
538
        }
539
    }
540
}
541