-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathActiveDocument.php
More file actions
98 lines (81 loc) · 2.83 KB
/
Copy pathActiveDocument.php
File metadata and controls
98 lines (81 loc) · 2.83 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace x1\data;
use Yii;
use yii\base\NotSupportedException;
/**
* The ActiveDocument class provides a wrapper/helpers to attach
* the ActiveDocumentBehavior at runtime to ActiveRecords.
*
* Example:
*
* $config = [
* 'defaultDelete' => true,
* 'defaultIgnoreError' => false,
* 'config' => [
* 'relations' => [
* 'mySubItems' => [
* 'incremental' => false,
* 'delete' => true,
* 'relations' => [
* 'moreSubItems' => [
* 'incremental' => false,
* ],
* ],
* ],
* ],
* ],
* ];
*
* ActiveDocument::find($model, $config, ['id' => 1])
*
*/
class ActiveDocument extends yii\base\Model
{
const ACTIVE_DOCUMENT = 'ActiveDocument';
public $relations = [];
public $useTransaction = true;
public $defaultIncremental = false;
public $defaultIgnoreError = false;
public $defaultDelete = true;
public $defaultScenario = null;
public $defaultSkipUpdate = false;
public $model = null;
public static function attach(&$model, $options) {
$model->attachBehavior(self::ACTIVE_DOCUMENT, new \x1\data\behaviors\ActiveDocumentBehavior($options));
}
private function getConfig() {
return [
'useTransaction' => $this->useTransaction,
'defaultIncremental' => $this->defaultIncremental,
'defaultIgnoreError' => $this->defaultIgnoreError,
'defaultDelete' => $this->defaultDelete,
'defaultScenario' => $this->defaultScenario,
'defaultSkipUpdate' => $this->defaultSkipUpdate,
'relations' => $this->relations,
];
}
private function checkModel() {
if (empty($this->model))
throw new \yii\base\InvalidConfigException("Model missing");
}
public function init() {
if (is_string($this->model))
$this->model = new $this->model();
$this->checkModel();
self::attach($this->model, $this->getConfig());
}
public function findOne($key) {
$result = $this->model->findWithRelations($key);
if ($result)
self::attach($result, $this->getConfig());
return $result;
}
public function load($data, $formName = null) {
$this->checkModel();
return $this->model->load($data, $formName);
}
public function getErrors($attribute = null) {
$this->checkModel();
return $this->model->getErrorDocument();
}
}