notes/src/Common/Reflected.php
2024-05-27 18:06:56 +00:00

86 lines
2.2 KiB
PHP

<?php
namespace Notes\Common;
use Notes\Attribute\Ignore;
abstract class Reflected
{
public function hasIgnoreAttribute() : bool
{
return [] !== array_filter($this->attributes, fn($e) => $e->object instanceof Ignore);
}
public function allowsNull() : bool
{
return empty($this->type) || $this->expectType("null");
}
public function expectType(string $type) : bool
{
$type = strtolower($type);
foreach($this->getTypes() as $item) {
if ($type === "null") {
if ($item->type === "null" || $item->nullable) {
return true;
}
}
elseif ($type === $item->type) {
return true;
}
}
return false;
}
public function getTypes() : array
{
return is_array($this->type) ? $this->type : [ $this->type ];
}
public function typeFromReflection(\ReflectionProperty|\ReflectionParameter $property) : void
{
if ( $property->hasType() ) {
$type = $property->getType();
if ($type instanceof \ReflectionUnionType ) {
foreach($type->getTypes() as $item) {
$this->type[] = new ReflectedPropertyType($item->getName(), $item->isBuiltIn(), $item->allowsNull());
}
}
else {
$this->type = new ReflectedPropertyType($type->getName(), $type->isBuiltIn(), $type->allowsNull());
}
}
}
public function getAttributes(?string $attributeType = null): array
{
if ($attributeType) {
$list = [];
foreach($this->attributes as $attribute) {
if ($attribute->object instanceof $attributeType) {
$list[] = $attribute;
}
}
return $list;
}
return $this->attributes;
}
public function getAttribute(string $attributeType): ?object
{
foreach($this->getAttributes($attributeType) as $attribute) {
if ($attribute->object instanceof $attributeType) {
return $attribute;
}
}
return null;
}
}