@ 2021-07-22T16:09:22Z <?php
declare(strict_types=1);
namespace Crell\ObjectAnalyzer;
class ObjectAnalyzer
{
public function analyze(string|object $class, string $attribute): object
{
$subject = match (is_string($class)) {
true => new \ReflectionClass($class),
false => new \ReflectionObject($class),
};
$classDef = $this->getAttribute($subject, $attribute) ?? new $attribute;
if ($classDef instanceof ReflectionPopulatable) {
$classDef->fromReflection($subject);
}
if ($classDef instanceof Fieldable) {
$fields = $this->getPropertyDefinitions($subject, $classDef::propertyAttribute());
$classDef->setFields($fields);
}
return $classDef;
}
/**
* @return Field[]
*/
protected function getPropertyDefinitions(\ReflectionObject|\ReflectionClass $subject, string $propertyAttribute): array
{
// The list of filters here is going to grow, so wants pipes.
$rProperties = $subject->getProperties();
// Wants PFA
$properties = array_map(fn(\ReflectionProperty $p) => $this->getPropertyDefinition($p, $propertyAttribute), $rProperties);
//$fields = array_filter($fields, fn(Field $f): bool => !$f->skip);
return $properties;
}
// Wants a generic return.
protected function getPropertyDefinition(\ReflectionProperty $property, string $propertyAttribute): object
{
$propDef = $this->getAttribute($property, $propertyAttribute) ?? new $propertyAttribute();
if ($propDef instanceof ReflectionPopulatable) {
$propDef->fromReflection($property);
}
return $propDef;
}
protected function getAttribute(\Reflector $target, string $name): ?object
{
return $this->getAttributes($target, $name)[0] ?? null;
}
protected function getAttributes(\Reflector $target, string $name): array
{
return array_map(fn(\ReflectionAttribute $attrib)
=> $attrib->newInstance(), $target->getAttributes($name, \ReflectionAttribute::IS_INSTANCEOF));
}
}
Enable javascript to submit You have javascript disabled. You will not be able to edit any code.
Output for 8.0.8 , 8.1.23 - 8.1.28 , 8.2.10 - 8.2.18 , 8.3.0 - 8.3.4 , 8.3.6 Output for 8.3.5 Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
preferences:dark mode live preview
75.55 ms | 402 KiB | 28 Q