Completed
Push — master ( 221967...a1a3f9 )
by Vitaly
03:06
created

dbQuery::limit()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 3
Metric Value
c 5
b 0
f 3
dl 0
loc 12
rs 9.4286
cc 2
eloc 6
nc 2
nop 3
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
     * Add condition by primary field
324
     *
325
     * @param string $value Primary field value
326
     * @return \samson\activerecord\dbQuery Chaining
327
     */
328
    public function id($value)
329
    {
330
        // PHP 5.2 get primary field
331
        eval('$_primary = ' . $this->class_name . '::$_primary;');
332
333
        // Set primary field value
334
        return $this->cond($_primary, $value);
0 ignored issues
show
Bug introduced by
The variable $_primary does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
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...
335
    }
336
337
    /**	 @see idbQuery::where() */
0 ignored issues
show
Coding Style introduced by
Spaces must be used for alignment; tabs are not allowed
Loading history...
338
    public function where($condition)
339
    {
340
        return $this->cond($condition, '', dbRelation::OWN);
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...
341
    }
342
343
    /** @deprecated Use self::fields() */
344
    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...
345
    {
346
        return call_user_func_array(array($this, 'fields'), func_get_args());
347
    }
348
349
    /** @see idbQuery::join() */
350
    public function join($tableName, $className = null, $ignore = false)
351
    {
352
        // Добавим имя класса в коллекцию присоединения
353
        $this->join[] = new RelationData($this->class_name, $tableName, $className, $ignore);
354
355
        // Вернем себя для цепирования
356
        return $this;
357
    }
358
359
    /** @see idbQuery::group_by() */
360
    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...
361
    {
362
        // Default grouping array
363
        $destination = &$this->group;
364
365
        // If this field belongs to query main class
366
        //if (property_exists( $this->class_name, $field )) $destination = & $this->own_group;
367
368
        $destination[] = $field;
369
370
        // Вернем себя для цепирования
371
        return $this;
372
    }
373
374
    /** @see idbQuery::limit() */
375
    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...
376
    {
377
        // Select base table or whole query destination
378
        if ($own) {
379
            $this->own_limit = array($st, $en);
380
        } else {
381
            $this->limit = array($st, $en);
382
        }
383
384
        // Вернем себя для цепирования
385
        return $this;
386
    }
387
388
    /** @see idbQuery::order_by() */
389
    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...
390
    {
391
        $this->order[] = array($field, $direction);
392
393
        // Вернем себя для цепирования
394
        return $this;
395
    }
396
397
    /** @see idbQuery::add_field() */
398
    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...
399
    {
400
        // Если передан псевдоним для поля, то подставим его
401
        if (isset($alias)) {
402
            $field = $field . ' as ' . $alias;
403
        } else {
404
            $alias = $field;
405
        }
406
407
        // Добавим виртуальное поле
408
        if ($own) {
409
            $this->own_virtual_fields[$alias] = $field;
410
        } else {
411
            $this->virtual_fields[$alias] = $field;
412
        }
413
414
        // Вернем себя для цепирования
415
        return $this;
416
    }
417
418
    /** @see idbQuery::count() */
419
    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...
420
    {
421
        return db()->count($this->class_name, $this);
422
    }
423
424
    /** @see idbQuery::innerCount() */
425
    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...
426
    {
427
        return db()->innerCount($this->class_name, $this);
428
    }
429
430
    /**	@see idbQuery::parse() */
0 ignored issues
show
Coding Style introduced by
Spaces must be used for alignment; tabs are not allowed
Loading history...
431
    public function parse($queryText, array $args = null)
432
    {
433
        // Преобразуем текст в нижний регистр
434
        //$query_text = mb_strtolower( $query_text, 'UTF-8' );
435
436
        // Паттерн для определения метода динамического запроса
437
        $sortingPattern = '
438
		/(?:^(?<method>find_by|find_all_by|all|first|last)_)
439
			|_order_by_  (?P<order>[a-zа-я0-9]+) _ (?P<order_dir>(?:asc|desc))
440
			|_limit_ (?P<limit_start>\d+) (?:_(?P<limit_end>\d+))?
441
			|_group_by_(?P<group>.+)
442
			|_join_ (?<join>.+)
443
		/iux';
444
445
        // Это внутренний счетчик для аргументов запроса для того чтобы не сбиться при их подставлении
446
        // в условие запроса к БД
447
        $argsCnt = 0;
448
449
        // Выполним первоначальный парсинг проверяющий правильность указанного метода
450
        // выборки данных и поиск возможных модификаторов запроса
451
        if (preg_match_all($sortingPattern, $queryText, $globalMatches)) {
452
            // Удалим все пустые группы полученные послке разпознования
453
            $globalMatches = array_filter_recursive($globalMatches);
454
455
            // Получим текст условий самого запроса, убрав из него все возможные модификаторы и параметры
456
            // и переберем только полученные группы условий запроса
457
            foreach (explode('_or_', str_ireplace($globalMatches[0], '', $queryText)) as $groupText) {
458
                // Добавим группу условий к запросу
459
                $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...
460
461
                // Переберем поля которые формируют условия запроса - создание объекты-условия запроса
462
                foreach (explode('_and_', $groupText) as $conditionText) {
463
                    $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...
464
                }
465
            }
466
467
            // Получим сортировку запроса
468
            if (isset($globalMatches['order'])) {
469
                $this->order = array($globalMatches['order'][0], $globalMatches['order_dir'][0]);
470
            }
471
            // Получим ограничения запроса
472
            if (isset($globalMatches['limit_start'])) {
473
                $this->limit = array($globalMatches['limit_start'][0], $globalMatches['limit_end'][0]);
474
            }
475
            // Получим групировку запроса
476 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...
477
                $this->group = explode('_and_', $globalMatches['group'][0]);
478
            }
479
            // Получим имена таблиц для "объединения" в запросе
480 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...
481
                foreach (explode('_and_', $globalMatches['join'][0]) as $join) {
482
                    $this->join($join);
483
                }
484
            }
485
        }
486
487
        // Вернем полученный объект-запрос
488
        return $this;
489
    }
490
491
    /**
492
     * Function to reconfigure dbQuery to work with multiple Entities
493
     *
494
     * @param string $className Entity name
495
     * @return self|string Chaining or current class name if nothing is passed
496
     */
497
    public function className($className = null)
498
    {
499
        if (!func_num_args()) {
500
            return $this->class_name;
501
        } else {
502
            $this->flush();
503
504
            if (isset($className)) {
505
                // Сформируем правильное имя класса
506
                $className = ns_classname($className, 'samson\activerecord');
0 ignored issues
show
Deprecated Code introduced by
The function ns_classname() has been deprecated with message: use \samson\core\AutoLoader::className() and pass full class name to it without splitting into class name and namespace

This function 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 function will be removed from the class and what other function to use instead.

Loading history...
507
                // Установим имя класса для запроса
508
                $this->class_name = $className;
509
            }
510
511
            return $this;
512
        }
513
    }
514
515
    // Magic method after-clonning
516
    public function __clone()
517
    {
518
        // Remove old references
519
        $condition = $this->condition;
520
        unset($this->condition);
521
522
        // Set new one on copied values
523
        $this->condition = $condition;
524
        $this->cConditionGroup = &$this->condition;
525
    }
526
527
    // Магический метод для выполнения не описанных динамических методов класса
528
    public function __call($methodName, array $arguments)
529
    {
530
        /** @var array $matches Prepared statement matches */
531
        $matches = array();
532
        // Если этот метод поддерживается - выполним запрос к БД
533
        if (preg_match('/^(find_by|find_all_by|all)/iu', $methodName, $matches)) {
534
            return db()->find($this->class_name, $this->parse($methodName, $arguments));
535
        } elseif (property_exists($this->class_name, $methodName)) { // Проверим существует ли у класса заданное поле
536
537
            // Если передан аргумент - расцениваем его как аргумент запроса
538
            if (sizeof($arguments) > 1) {
539
                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...
540
            } elseif (isset($arguments[0])) {
541
                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...
542
            } else { // Просто игнорируем условие
543
                return $this;
544
            }
545
        } else { // Сообщим об ошибке разпознования метода
546
            return e(
547
                'Не возможно определить метод(##) для создания запроса к БД',
548
                E_SAMSON_ACTIVERECORD_ERROR,
549
                $methodName
550
            );
551
        }
552
    }
553
554
    /**
555
     * Конструктор
556
     * @param string|null 	$className  Имя класса для которого создается запрос к БД
0 ignored issues
show
Coding Style introduced by
Spaces must be used for alignment; tabs are not allowed
Loading history...
557
     * @param mixed		    $link		Указатель на экземпляр подключения к БД
0 ignored issues
show
Coding Style introduced by
Spaces must be used for alignment; tabs are not allowed
Loading history...
558
     */
559
    public function __construct($className = null, & $link = null)
560
    {
561
        /*
562
        // Проверим класс
563
        if( !class_exists( $class_name ) )
564
        {
565
            e(
566
                'Не возможно создать запрос БД для класса(##) - Класс не существует',
567
                E_SAMSON_ACTIVERECORD_ERROR,
568
                $class_name
569
            );
570
        }
571
        */
572
573
        $this->className($className);
574
575
        // Сохраним экземпляр соединения
576
        $this->link = $link;
577
    }
578
}
579