-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindByAttribute.php
70 lines (57 loc) · 1.83 KB
/
FindByAttribute.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
/**
* @author Vadim Trunov <[email protected]>
*
* @copyright (C) 2017 - Bigdrop Inc
*
* @license https://opensource.org/licenses/BSD-3-Clause
*/
namespace bigdropinc\db;
use Yii;
use yii\helpers\BaseInflector;
trait FindByAttribute
{
public static function getFindByAttributeName($name)
{
if(strpos($name, 'findAllBy') === 0){
$attributeName = BaseInflector::underscore(str_replace('findAllBy', '', $name));
}
else if(strpos($name, 'findBy') === 0){
$attributeName = BaseInflector::underscore(str_replace('findBy', '', $name));
}
return isset($attributeName) && static::isColumnExist($attributeName) ? $attributeName : null;
}
public static function getFindByMethodName($name)
{
if(strpos($name, 'findAllBy') === 0){
return 'all';
}
else if(strpos($name, 'findBy') === 0){
return 'one';
} else {
return null;
}
}
public static function isFindByCanProcess($name)
{
return !empty(static::getFindByAttributeName($name));
}
public static function processFindBy($name, $arguments)
{
if($attributeName = static::getFindByAttributeName($name)){
$findMethod = static::getFindByMethodName($name);
$value = $arguments[0];
return static::callFindByMethod($findMethod, $attributeName, $value);
}
}
public static function callFindByMethod($findMethod, $attributeName, $value)
{
$query = static::find()->where([static::tableName().'.'.$attributeName => $value]);
return $query->$findMethod();
}
private static function isColumnExist($column)
{
$table = Yii::$app->db->schema->getTableSchema(static::tableName());
return isset($table->columns[$column]);
}
}