1 | <?php |
||
34 | class EmbeddedDecorator implements DecoratorInterface |
||
35 | { |
||
36 | |||
37 | 17 | public function read($model, $name, &$dbValue, $transformatorClass = TransformatorInterface::class) |
|
38 | { |
||
39 | 17 | if (is_object($dbValue) && $dbValue instanceof AnnotatedInterface) |
|
40 | { |
||
41 | $model->$name = $dbValue; |
||
42 | return; |
||
43 | } |
||
44 | 17 | if($dbValue === null) |
|
45 | { |
||
46 | 1 | $meta = ManganMeta::create($model)->$name; |
|
47 | 1 | if($meta->embedded && $meta->embedded->nullable) |
|
48 | { |
||
49 | 1 | $model->$name = null; |
|
50 | 1 | return null; |
|
51 | } |
||
52 | } |
||
53 | 16 | static::ensureClass($model, $name, $dbValue); |
|
54 | 16 | $instance = null; |
|
55 | 16 | if ($model->$name instanceof $dbValue['_class']) |
|
56 | { |
||
57 | 1 | $instance = $model->$name; |
|
58 | } |
||
59 | 16 | $embedded = $transformatorClass::toModel($dbValue, $instance, $instance); |
|
60 | |||
61 | // Field was transformed from DB Ref |
||
62 | 16 | $embedded = DbRefManager::maybeCreateInstanceFrom($embedded); |
|
63 | |||
64 | 16 | $model->$name = $embedded; |
|
65 | 16 | } |
|
66 | |||
67 | 25 | public function write($model, $name, &$dbValue, $transformatorClass = TransformatorInterface::class) |
|
68 | { |
||
69 | 25 | if (null === $model->$name) |
|
70 | { |
||
71 | 4 | $meta = ManganMeta::create($model)->$name; |
|
72 | 4 | if($meta->embedded && $meta->embedded->nullable) |
|
73 | { |
||
74 | 1 | $dbValue[$name] = null; |
|
75 | 1 | return null; |
|
76 | } |
||
77 | 3 | $className = static::getClassName($model, $name); |
|
78 | 3 | if (!is_string($className)) |
|
79 | { |
||
80 | 1 | return null; |
|
81 | } |
||
82 | // This is to prevent infinite loops |
||
83 | // if class name is same as current `$model`, ie not really set. |
||
84 | // @link https://github.com/Maslosoft/Mangan/issues/86 |
||
85 | 2 | if(is_a($model, $className)) |
|
86 | { |
||
87 | return null; |
||
88 | } |
||
89 | 2 | $dbValue[$name] = $transformatorClass::fromModel(new $className); |
|
90 | 2 | return; |
|
91 | } |
||
92 | 21 | $dbValue[$name] = $transformatorClass::fromModel($model->$name); |
|
93 | 21 | } |
|
94 | |||
95 | 21 | public static function ensureClass($model, $name, &$dbValue) |
|
134 | |||
135 | 3 | protected static function getClassName($model, $name) |
|
142 | |||
143 | } |
||
144 |