-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathBaseWorkOSResource.php
More file actions
106 lines (88 loc) · 2.36 KB
/
BaseWorkOSResource.php
File metadata and controls
106 lines (88 loc) · 2.36 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
99
100
101
102
103
104
105
106
<?php
namespace WorkOS\Resource;
class BaseWorkOSResource
{
/**
* Maps response keys to resource keys.
* Child classes should override this constant.
*
* @var array<string, string>
*/
protected const RESPONSE_TO_RESOURCE_KEY = [];
/**
* List of attributes available in this resource.
* Child classes should override this constant.
*
* @var array<string>
*/
protected const RESOURCE_ATTRIBUTES = [];
/**
* @var array $values;
*/
protected $values;
/**
* @var array $raw;
*/
public $raw;
private function __construct()
{
}
/**
* Creates a Resource from a Response.
*
* @param array<string, mixed> $response
*
* @return static
*/
public static function constructFromResponse($response)
{
$instance = new static();
$instance->raw = $response;
$instance->values = [];
foreach (static::RESPONSE_TO_RESOURCE_KEY as $responseKey => $resourceKey) {
try {
$instance->values[$resourceKey] = $instance->raw[$responseKey] ?? null;
} catch (\OutOfBoundsException $e) {
$instance->values[$resourceKey] = null;
}
}
return $instance;
}
public function toArray()
{
return \array_reduce(static::RESOURCE_ATTRIBUTES, function ($arr, $key) {
$arr[$key] = $this->values[$key];
return $arr;
}, []);
}
/**
* Magic method overrides.
*/
public function __set($key, $value)
{
if (\in_array($key, static::RESOURCE_ATTRIBUTES)) {
$this->values[$key] = $value;
}
$msg = "{$key} does not exist on " . static::class . ".";
throw new \WorkOS\Exception\UnexpectedValueException($msg);
}
public function __isset($key)
{
return isset($this->values[$key]);
}
public function __unset($key)
{
unset($this->values[$key]);
}
public function &__get($key)
{
if (\in_array($key, static::RESOURCE_ATTRIBUTES)) {
return $this->values[$key];
}
if (isset($this->raw[$key])) {
return $this->raw[$key];
}
$msg = "{$key} does not exist on " . static::class . ".";
throw new \WorkOS\Exception\UnexpectedValueException($msg);
}
}