Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
TiiFuchs committed Apr 30, 2022
1 parent 5b052de commit e02e1a9
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 14 deletions.
2 changes: 1 addition & 1 deletion src/TelegramBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public function raw(string $method, $data = []): mixed
throw new \Exception($jsonResponse['description']);
}

public function objectify(string $method, mixed $result): mixed
private function objectify(string $method, mixed $result): mixed
{
$methodReflector = new \ReflectionMethod($this, $method);
$returnTypes = $methodReflector->getReturnType();
Expand Down
77 changes: 64 additions & 13 deletions src/Type.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,15 @@ class Type
public function __construct(array $data)
{
foreach ($data as $key => $value) {
$property = new \ReflectionProperty($this, $key);

$type = $property->getType();
if ($type instanceof \ReflectionNamedType && ! $type->isBuiltin()) {

$class = $type->getName();
$value = new $class($value);

} elseif ($type->getName() === 'array'
&& preg_match('/@var (.+)\[]\n/u', $property->getDocComment(), $matches) === 1) {

$class = 'Tii\\Telepath\\Telegram\\' . $matches[1];
$value = array_map(fn($entity) => new $class($entity), $value);

try {
$value = $this->objectify($key, $value);
} catch (\ReflectionException $e) {
//
}

$this->$key = $value;

}
}

Expand All @@ -33,4 +25,63 @@ public function toArray(): array
return get_object_vars($this);
}

private function objectify(string $key, mixed $value): mixed
{
$property = new \ReflectionProperty($this, $key);

$types = $property->getType();
$docComment = $property->getDocComment();

if ($types instanceof \ReflectionUnionType) {
$types = $types->getTypes();
} elseif ($types instanceof \ReflectionNamedType) {
$types = [$types];
} else {
throw new \Exception(sprintf(
"Incompatible type %s for key %s in %s",
get_class($types),
$key,
get_class($this)
));
}

foreach ($types as $type) {

if ($type->isBuiltin() && $type->getName() !== 'array') {

if ($type->getName() === get_debug_type($value)) {
return $value;
}

} elseif (is_array($value) && $type->getName() === 'array') {

if (preg_match('/@var (.+)\[]\n/u', $docComment, $matches) !== 1) {
continue;
}

$class = 'Tii\\Telepath\\Telegram\\' . $matches[1];

if (! class_exists($class)) {
continue;
}

return array_map(fn($data) => new $class($data), $value);

} elseif (is_array($value)) {

$class = $type->getName();

if (! class_exists($class)) {
continue;
}

return new $class($value);

}

}

return $value;
}

}

0 comments on commit e02e1a9

Please sign in to comment.