include missing

This commit is contained in:
icefox 2026-02-18 19:19:07 -03:00
parent 88b5850c32
commit d3e12785bb
No known key found for this signature in database
20 changed files with 584 additions and 4 deletions

View file

@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
namespace Icefox\DTO\Support;
use Illuminate\Support\Facades\App;
use ReflectionNamedType;
use ReflectionParameter;
use phpDocumentor\Reflection\PseudoTypes\Generic;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\AbstractList;
use phpDocumentor\Reflection\Types\Boolean;
use phpDocumentor\Reflection\Types\Float_;
use phpDocumentor\Reflection\Types\Integer;
use phpDocumentor\Reflection\Types\Nullable;
use phpDocumentor\Reflection\Types\Object_;
class ValueFactory
{
public static function constructObject(string $className, mixed $rawValue): object
{
if ($mapper = config('dto.mappers.' . $className, null)) {
return $mapper($rawValue);
}
if (is_array($rawValue)) {
return App::makeWith($className, $rawValue);
}
return new $className($rawValue);
}
public static function resolveTypedValue(mixed $rawValue, Type $type): mixed
{
if ($type instanceof Nullable) {
$type = $type->getActualType();
}
if ($type instanceof Generic) {
$types = $type->getTypes();
$innerType = count($types) === 2 ? $types[1] : $types[0];
$result = [];
foreach ($rawValue as $key => $value) {
$result[$key] = self::resolveTypedValue($value, $innerType);
}
return new ($type->getFqsen()->__toString())($result);
}
if ($type instanceof AbstractList) {
$innerType = $type->getValueType();
$result = [];
foreach ($rawValue as $key => $value) {
$result[$key] = self::resolveTypedValue($value, $innerType);
}
return $result;
}
if ($type instanceof Boolean) {
return boolval($rawValue);
}
if ($type instanceof Float_) {
return floatval($rawValue);
}
if ($type instanceof Integer) {
return intval($rawValue);
}
if ($type instanceof Object_) {
return self::constructObject($type->getFqsen()->__toString(), $rawValue);
}
return $rawValue;
}
public static function resolveValue(mixed $rawValue, ?Type $type, ReflectionParameter $reflection): mixed
{
if ($reflection->allowsNull() && is_null($rawValue)) {
return null;
}
if (is_null($type)) {
$reflectedType = $reflection->getType();
if ($reflectedType instanceof ReflectionNamedType && $name = $reflectedType->getName()) {
return match ($name) {
'string' => $rawValue,
'bool' => boolval($rawValue),
'int' => intval($rawValue),
'float' => floatval($rawValue),
'array' => $rawValue,
default => self::constructObject($name, $rawValue),
};
}
return $rawValue;
}
return self::resolveTypedValue($rawValue, $type);
}
}