This repository has been archived by the owner on Feb 26, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ObjectModel.php
213 lines (180 loc) · 6.36 KB
/
ObjectModel.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
<?php
/**
* @link https://github.com/gromver/yii2-models.git#readme
* @copyright Copyright (c) Gayazov Roman, 2014
* @license https://github.com/gromver/yii2-models/blob/master/LICENSE
* @package yii2-models
* @version 1.0.0
*/
namespace gromver\models;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
use yii\base\Object;
use yii\helpers\StringHelper;
/**
* Class Model
* @package yii2-models
* @author Gayazov Roman <gromver5@gmail.com>
*
* Моделька основанная на публичных полях данного объекта
*/
class ObjectModel extends DynamicModel implements ObjectModelInterface
{
private static $_specifications = [];
private static $_callStack = [];
private static $_callContext = [];
private $_source;
private $_sourceClass;
/**
* @param string|object $source
* @param array $config
* @throws \yii\base\InvalidParamException
* @internal param array $attributes
*/
public function __construct($source, $config = [])
{
if (is_string($source)) {
$this->_sourceClass = $source;
}
elseif (is_object($source)) {
$this->_source = $source;
$this->_sourceClass = get_class($source);
} else {
throw new InvalidParamException('$source must be an object or a class name.');
}
Object::__construct($config);
}
/**
* @inheritdoc
*/
public function init()
{
//Проверка на зацикленность полей модели
$beginner = !count(self::$_callStack);
self::$_callContext[] = $this->_sourceClass;
self::$_callStack[md5(json_encode(self::$_callContext))] = $this->_sourceClass;
if (count(array_keys(self::$_callStack, $this->_sourceClass)) > 1) {
throw new InvalidConfigException('Infinite loop detected.');
}
//инициализация
$specification = $this->getClassSpecification($this->_sourceClass);
if ($this->_source instanceof SpecificationInterface) {
$this->_source->processSpecification($specification);
}
foreach ($specification as $attribute => $settings) {
//своиства класса с анотацией @ignore игнорируются))
if (isset($settings['ignore']))
continue;
//определяем атрибут для модели
$this->defineAttribute($attribute, $settings);
//если в качестве структуры дан обьект, то инициализируем модель значениями объекта
if (isset($this->_source) && isset($this->_source->{$attribute})) {
$this->{$attribute} = $this->_source->{$attribute};
}
}
//очищаем текущий контекст
array_pop(self::$_callContext);
//очищаем стек, для проверки бесконечного цикла, если он был начат данной моделью
if ($beginner) {
self::$_callStack = [];
}
}
/**
* @inheritdoc
*/
public function formName()
{
$event = new FormNameEvent(['formName' => StringHelper::basename($this->_sourceClass)]);
$this->trigger(self::EVENT_FORM_NAME, $event);
return $event->formName;
}
/**
* хелпер - для запуска функций принадлежащих self::sourceClass, используется статический контекст
* в качестве параметра в функцию передается модель
* @param $funcName string
* @return mixed
*/
public function invoke($funcName)
{
return call_user_func([$this->_sourceClass, $funcName], $this);
}
/**
* @return object|string
* @throws InvalidConfigException
*/
public function getSource()
{
return isset($this->_source) ? $this->_source : \Yii::createObject($this->_sourceClass);
}
/**
* @return string
*/
public function getSourceClass()
{
return $this->_sourceClass;
}
/**
* @param $className
* @return mixed
*/
public static function getClassSpecification($className)
{
if(!isset(self::$_specifications[$className]))
{
$specification = [];
$reflection = new \ReflectionClass($className);
$properties = $reflection->getProperties(\ReflectionProperty::IS_PUBLIC);
$defaultProperties = $reflection->getDefaultProperties();
foreach($properties as $property)
{
if ($property->isStatic()) continue;
$settings = self::processProperty($property);
if (!isset($settings['default'])) {
$settings['default'] = $defaultProperties[$property->getName()];
}
$specification[$property->getName()] = $settings;
}
self::$_specifications[$className] = $specification;
}
return self::$_specifications[$className];
}
/**
* @param $property \ReflectionProperty
* @return array
*/
private static function processProperty($property)
{
$comment=$property->getDocComment();
$comment=strtr($comment,array("\r\n"=>"\n","\r"=>"\n")); // make line endings consistent: win -> unix, mac -> unix
$comment=preg_replace('/^\s*\**(\s*?$|\s*)/m','',$comment);
$settings = [];
if($n=preg_match_all('/^@(\w+)(.*)$/im',$comment,$matches))
{
for($i=0;$i<$n;++$i)
{
$attrName = strtolower($matches[1][$i]);
$attrValue = trim($matches[2][$i]);
$settings[$attrName] = $attrValue;
}
}
return $settings;
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return array_map(function($field) {
/** @var $field \gromver\models\fields\BaseField */
return $field->label ? $field->label : $this->generateAttributeLabel($field->attribute);
}, $this->modelFields());
}
// ObjectModelInterface
/**
* @inheritdoc
*/
public function getObjectModel()
{
return $this;
}
}