- Fixed some non-nullable defaulted to null vars in functions - Added a new diff method for entities which skips nullable values if they are not defined.
76 lines
2.3 KiB
PHP
76 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace Ulmus\Attribute\Property;
|
|
|
|
use Notes\Common\ReflectedProperty;
|
|
use Ulmus\Entity\EntityInterface;
|
|
use Ulmus\Entity\JsonUnserializable;
|
|
|
|
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
|
class ArrayOf implements \Ulmus\Entity\EntityValueModifier
|
|
{
|
|
public function __construct(
|
|
public readonly string $type,
|
|
) {}
|
|
|
|
public function push(mixed $value, ReflectedProperty $property): mixed
|
|
{
|
|
$return = [];
|
|
|
|
foreach($value as $index => $item) {
|
|
if (! is_object($item)) {
|
|
if (enum_exists($this->type)) {
|
|
if ($this->type::tryFrom($item) === null) {
|
|
throw new \InvalidArgumentException(
|
|
sprintf("Given item '%s' is not a valid enum for type %s ; try one of theses instead : %s", $item, $this->type, implode("', '", array_map(fn($e) => $e->value, $this->type::cases())))
|
|
);
|
|
} else {
|
|
$obj = $this->type::from($item);
|
|
}
|
|
}
|
|
elseif (class_exists($this->type)) {
|
|
if (is_subclass_of($this->type, JsonUnserializable::class)) {
|
|
$obj = (new \ReflectionClass($this->type))->newInstanceWithoutConstructor();
|
|
$obj->jsonUnserialize($item);
|
|
}
|
|
else {
|
|
$obj = new $this->type($item);
|
|
}
|
|
}
|
|
else {
|
|
throw new \InvalidArgumentException("Given type for ArrayOf is incompatible with it's use. An object should be provided");
|
|
}
|
|
|
|
$return[$index] = $obj;
|
|
}
|
|
}
|
|
|
|
if (! $property->type->builtIn) {
|
|
$cls = $property->type->type;
|
|
|
|
return new $cls($return);
|
|
}
|
|
|
|
return $return;
|
|
}
|
|
|
|
public function pull(mixed $value, ReflectedProperty $property) : mixed
|
|
{
|
|
$return = [];
|
|
|
|
foreach($value as $index => $item) {
|
|
if (is_object($item)) {
|
|
if (enum_exists($this->type)) {
|
|
$value = $item->value;
|
|
} elseif (class_exists($this->type)) {
|
|
$value = (string) $value;
|
|
}
|
|
|
|
$return[$index] = $value;
|
|
}
|
|
}
|
|
|
|
return $return;
|
|
}
|
|
|
|
} |