-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathHydratedAttributes.php
73 lines (66 loc) · 2.27 KB
/
HydratedAttributes.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
71
72
73
<?php
/**
* @link http://www.diemeisterei.de/
* @copyright Copyright (c) 2014 diemeisterei GmbH, Stuttgart
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace dmstr\db\behaviors;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use yii\db\Exception;
/**
* Class CouchDocument
* @package common\models
* @author Tobias Munk <[email protected]>
*/
class HydratedAttributes extends Behavior
{
/**
* @var column to use for array keys; has to be unique
*/
public $keyAttribute;
private $_m;
private $_d;
public function getHydratedAttributes()
{
$attributes = $this->owner->attributes;
$this->parseAttributesRecursive($this->owner, $attributes);
return $attributes;
}
/**
* @param $model The model which attributes should be parsed recursively
* @param $attributes Variable which holds the attributes
*/
private function parseAttributesRecursive($model, &$attributes)
{
foreach ($model->relatedRecords AS $name => $relation) {
if (is_array($relation)) {
// many_many relation
$attributes[$name] = [];
foreach ($relation AS $rModel) {
$d = $rModel->attributes;
$this->parseAttributesRecursive($rModel, $d);
// create index from column (Note: column has to be unique)
if ($rModel->getBehavior('hydratedAttributes') && $rModel->keyAttribute) {
if (isset($attributes[$name][$d[$rModel->keyAttribute]])) {
throw new Exception("Index '{$d[$rModel->keyAttribute]}' not unique");
} else {
$attributes[$name][$d[$rModel->keyAttribute]] = $d;
}
} else {
$attributes[$name][] = $d;
}
}
} else {
if ($relation instanceof ActiveRecord) {
// non-multiple
$attributes[$name] = $relation->attributes;
} else {
$attributes[$name] = null;
}
}
}
}
}