-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathBlueprint.php
More file actions
87 lines (71 loc) · 2.45 KB
/
Blueprint.php
File metadata and controls
87 lines (71 loc) · 2.45 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
<?php namespace Locker\XApi;
use Locker\XApi\Errors\Error as Error;
class Blueprint extends Element {
const LOCKER_NAMESPACE = 'Locker\XApi\\';
protected $default_type = 'Element';
protected $accepted_types = [];
protected $type_prop = 'objectType';
public function __construct($value = null) {
if ($value === null) return;
$this->setValue($value);
}
public function setValue($new_value) {
if (gettype($new_value) !== 'object') {
$this->value = $new_value;
return $this;
}
$previous_type = $this->value instanceof Element ? $this->value->getProp($this->type_prop) : null;
$new_type = isset($new_value->{$this->type_prop}) ? $new_value->{$this->type_prop} : null;
$type = $new_type ?: $previous_type ?: $this->default_type;
if ($new_value !== null) {
$new_value->{$this->type_prop} = $type;
if (!in_array($type, $this->accepted_types)) {
$type = 'Element';
}
$lockerClass = self::LOCKER_NAMESPACE.$type;
$this->value = new $lockerClass($this->value);
$this->value->setValue($new_value);
}
return $this;
}
protected function getSetProps($object = null) {
return parent::getSetProps($object);
}
public function getValue() {
if (gettype($this->value) !== 'object') {
return $this->value;
}
return $this->value->getValue();
}
public function validate() {
$value_type = gettype($this->value);
if (gettype($this->value) !== 'object') {
$encoded_value = json_encode($this->value);
return [new Error("`$encoded_value` must be `object` not `$value_type`")];
}
$errors = [];
if ($this->value !== null) {
$type = $this->value->getProp($this->type_prop);
$type = $type instanceof Atom ? $type->getValue() : $type;
if (!in_array($type, $this->accepted_types)) {
$errors[] = new Error(
"`$type` (".get_class($this->value).") is not a valid `{$this->type_prop}` in `".get_class($this).'`. Acceptable types are `'.implode(', ', $this->accepted_types).'`'
);
}
}
return array_merge($errors, $this->value->validate());
}
public function setProp($prop_key, $prop_value) {
if (gettype($this->value) !== 'object') {
return $this;
}
$this->value->setProp($prop_key, $prop_value);
return $this;
}
public function getProp($prop_key) {
if (gettype($this->value) !== 'object') {
return null;
}
return $this->value->getProp($prop_key);
}
}