|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace rhertogh\Yii2Oauth2Server\models\traits; |
|
4
|
|
|
|
|
5
|
|
|
use rhertogh\Yii2Oauth2Server\interfaces\models\base\Oauth2ActiveRecordInterface; |
|
6
|
|
|
use Yii; |
|
7
|
|
|
use yii\base\InvalidArgumentException; |
|
8
|
|
|
use yii\base\InvalidConfigException; |
|
9
|
|
|
use yii\db\ActiveRecord; |
|
10
|
|
|
use yii\db\Exception as DbException; |
|
11
|
|
|
use yii\db\TableSchema; |
|
12
|
|
|
use yii\helpers\ArrayHelper; |
|
13
|
|
|
|
|
14
|
|
|
trait Oauth2ActiveRecordTrait |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @param int|string|int[]|string[] $pk |
|
18
|
|
|
* @return static |
|
19
|
|
|
*/ |
|
20
|
12 |
|
public static function findByPk($pk) |
|
21
|
|
|
{ |
|
22
|
12 |
|
if (empty($pk)) { |
|
23
|
1 |
|
throw new InvalidArgumentException('$pk can not be empty.'); |
|
24
|
|
|
} |
|
25
|
|
|
/** @var TableSchema $tableSchema */ |
|
26
|
11 |
|
$tableSchema = static::getTableSchema(); |
|
27
|
11 |
|
$numPkColumns = count($tableSchema->primaryKey); |
|
28
|
11 |
|
if ($numPkColumns === 1) { |
|
29
|
11 |
|
$primaryKey = [$tableSchema->primaryKey[0] => (is_array($pk) ? reset($pk) : $pk)]; |
|
30
|
|
|
} elseif ($numPkColumns > 1) { |
|
31
|
|
|
$primaryKey = []; |
|
32
|
|
|
foreach ($tableSchema->primaryKey as $column) { |
|
33
|
|
|
if (empty($pk[$column])) { |
|
34
|
|
|
throw new InvalidArgumentException('$pk[' . $column . '] can not be empty.'); |
|
35
|
|
|
} |
|
36
|
|
|
$primaryKey[$column] = $pk[$column]; |
|
37
|
|
|
} |
|
38
|
|
|
} else { |
|
39
|
|
|
throw new InvalidConfigException(static::class . ' is missing a primary key.'); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
11 |
|
return static::findOne($primaryKey); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* @inheritDoc |
|
47
|
|
|
*/ |
|
48
|
1 |
|
public static function findOrCreate($condition) |
|
49
|
|
|
{ |
|
50
|
1 |
|
$activeRecord = static::findOne($condition); |
|
51
|
|
|
|
|
52
|
1 |
|
if (empty($activeRecord)) { |
|
53
|
1 |
|
$activeRecord = Yii::createObject(ArrayHelper::merge($condition, [ |
|
54
|
1 |
|
'class' => static::class, |
|
55
|
1 |
|
])); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
1 |
|
return $activeRecord; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* @inheritDoc |
|
63
|
|
|
*/ |
|
64
|
6 |
|
public function persist($runValidation = true, $attributeNames = null) |
|
65
|
|
|
{ |
|
66
|
|
|
/** @var ActiveRecord|Oauth2ActiveRecordInterface $this */ |
|
67
|
6 |
|
if (!$this->save($runValidation, $attributeNames)) { |
|
68
|
|
|
throw new DbException('Could not save ' . static::class . |
|
69
|
|
|
(YII_DEBUG ? PHP_EOL . print_r($this->attributes, true) : '') . |
|
|
|
|
|
|
70
|
|
|
' Errors: ' . PHP_EOL . implode(', ', $this->getErrorSummary(true))); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
6 |
|
return $this; |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|