forked from plesk/api-php-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAbstractStruct.php
75 lines (67 loc) · 2.3 KB
/
AbstractStruct.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
<?php
// Copyright 1999-2022. Plesk International GmbH.
namespace PleskX\Api;
abstract class AbstractStruct
{
/**
* @param string $property
* @param mixed $value
*
* @throws \Exception
*/
public function __set(string $property, $value)
{
throw new \Exception("Try to set an undeclared property '$property' to a value: $value.");
}
/**
* Initialize list of scalar properties by response.
*
* @param \SimpleXMLElement $apiResponse
* @param array $properties
*
* @throws \Exception
*/
protected function initScalarProperties($apiResponse, array $properties): void
{
foreach ($properties as $property) {
if (is_array($property)) {
$classPropertyName = current($property);
$value = $apiResponse->{key($property)};
} else {
$classPropertyName = $this->underToCamel(str_replace('-', '_', $property));
$value = $apiResponse->$property;
}
$reflectionProperty = new \ReflectionProperty($this, $classPropertyName);
$propertyType = $reflectionProperty->getType();
if (is_null($propertyType)) {
$docBlock = $reflectionProperty->getDocComment();
$propertyType = preg_replace('/^.+ @var ([a-z]+) .+$/', '\1', $docBlock);
} else {
/** @psalm-suppress UndefinedMethod */
$propertyType = $propertyType->getName();
}
if ('string' == $propertyType) {
$value = (string) $value;
} elseif ('int' == $propertyType) {
$value = (int) $value;
} elseif ('bool' == $propertyType) {
$value = in_array((string) $value, ['true', 'on', 'enabled']);
} else {
throw new \Exception("Unknown property type '$propertyType'.");
}
$this->$classPropertyName = $value;
}
}
/**
* Convert underscore separated words into camel case.
*
* @param string $under
*
* @return string
*/
private function underToCamel(string $under): string
{
$under = '_' . str_replace('_', ' ', strtolower($under));
return ltrim(str_replace(' ', '', ucwords($under)), '_');
}
}