dep,refac: DTO를 composer 외부로 이동

This commit is contained in:
2022-08-05 23:43:38 +09:00
parent f8cd58bcb3
commit da27ae2bad
27 changed files with 90 additions and 1264 deletions
-44
View File
@@ -1,44 +0,0 @@
<?php
namespace sammo\DTO\Attr;
use sammo\DTO\Converter\Converter;
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_CLASS)]
class Convert
{
public Converter $converter;
public array $targetTypes;
public readonly array $args;
public function __construct(
public readonly string $converterType,
...$args
) {
if(!is_subclass_of($converterType, \sammo\DTO\Converter\Converter::class)){
throw new \Exception("$converterType is not a subclass of DTO\Converter\Converter");
}
$this->args = $args;
}
public function setType(array $targetTypes): self{
$this->targetTypes = $targetTypes;
$converterType = $this->converterType;
$this->converter = new $converterType($targetTypes, ...$this->args);
return $this;
}
public function convertFrom(string|array|int|float|bool|null $raw, string $name): mixed
{
if($this->converter === null){
throw new \Exception("converter[{$name}] is not set");
}
return $this->converter->convertFrom($raw, $name);
}
public function convertTo(mixed $target): string|array|int|float|bool|null {
if($this->converter === null){
throw new \Exception('converter is not set');
}
return $this->converter->convertTo($target);
}
}
-16
View File
@@ -1,16 +0,0 @@
<?php
namespace sammo\DTO\Attr;
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class DefaultValue
{
public function __construct(public readonly null|bool|int|float|string|array $defaultValue)
{
}
public function getDefaultValue(): mixed
{
return $this->defaultValue;
}
}
@@ -1,20 +0,0 @@
<?php
namespace sammo\DTO\Attr;
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class DefaultValueGenerator
{
public function __construct(public readonly string $generator)
{
if (!is_callable($generator)) {
throw new \Exception("$generator is not a callable");
}
}
public function getDefaultValue(): mixed
{
$generator = $this->generator;
return $generator();
}
}
-11
View File
@@ -1,11 +0,0 @@
<?php
namespace sammo\DTO\Attr;
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class Ignore
{
public function __construct()
{
}
}
-13
View File
@@ -1,13 +0,0 @@
<?php
namespace sammo\DTO\Attr;
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class JsonString
{
public function __construct(
public readonly bool $emptyItemIsArray = false,
public readonly int $jsonFlag = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
) {
}
}
-11
View File
@@ -1,11 +0,0 @@
<?php
namespace sammo\DTO\Attr;
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class NullIsUndefined
{
public function __construct()
{
}
}
-11
View File
@@ -1,11 +0,0 @@
<?php
namespace sammo\DTO\Attr;
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class RawName
{
public function __construct(public readonly string $rawName)
{
}
}
@@ -1,43 +0,0 @@
<?php
namespace sammo\DTO\Converter;
class ArrayConverter implements Converter
{
private Converter $itemConverter;
public function __construct(private array $types, array $itemTypes, ?string $itemConverterClass = null, ...$args)
{
if(!is_array($itemTypes)){
throw new \Exception('itemTypes is not a array');
}
if($itemConverterClass === null){
$itemConverterClass = DefaultConverter::class;
}
else if(!is_subclass_of($itemConverterClass, Converter::class)){
throw new \Exception("$itemConverterClass is not a subclass of \sammo\DTO\Converter\Converter");
}
$this->itemConverter = new $itemConverterClass($itemTypes, ...$args);
}
public function convertFrom(string|array|int|float|bool|null $raw, string $name): mixed
{
if ($raw === null && array_search('null', $this->types, true) !== false) {
return null;
}
if (!is_array($raw) || !array_is_list($raw)) {
throw new \Exception("value is not a array: $name");
}
return array_map(fn ($v) => $this->itemConverter->convertFrom($v, $name), $raw);
}
public function convertTo(mixed $data): string|array|int|float|bool|null
{
if ($data === null && array_search('null', $this->types) !== false) {
return null;
}
if (!is_array($data) || !array_is_list($data)) {
throw new \Exception('value is not a array');
}
return array_map(fn ($v) => $this->itemConverter->convertTo($v), $data);
}
}
-7
View File
@@ -1,7 +0,0 @@
<?php
namespace sammo\DTO\Converter;
interface Converter{
public function convertFrom(string|array|int|float|bool|null $raw, string $name): mixed;
public function convertTo(mixed $data): string|array|int|float|bool|null;
}
@@ -1,89 +0,0 @@
<?php
namespace sammo\DTO\Converter;
class DateTimeConverter implements Converter
{
const YMD_HIS = 'Y-m-d H:i:s';
const YMD_HISU = 'Y-m-d H:i:s.u';
protected \DateTimeZone $timeZoneOffset;
public function __construct(private array $types, string|int|float|null $timezone = null, public readonly string $datetimeFormat = self::YMD_HIS)
{
$this->timeZoneOffset = static::extractDateTimeZone($timezone);
}
private static function extractDateTimeZone(string|int|float|null $timezone): \DateTimeZone
{
if ($timezone === null) {
return new \DateTimeZone(date_default_timezone_get());
}
if (is_int($timezone)) {
if ($timezone < -12 || $timezone > 14) {
throw new \InvalidArgumentException('TimeZone argument must be between -12 and 14');
}
if ($timezone > 0) {
$offset = sprintf('+%02d00', $timezone);
} else {
$offset = sprintf('-%02d00', abs($timezone));
}
return new \DateTimeZone($offset);
}
if (is_float($timezone)) {
if ($timezone < -12 || $timezone > 14) {
throw new \InvalidArgumentException('TimeZone argument must be between -12 and 14');
}
$isPositive = $timezone > 0;
$offset = abs($timezone);
$hour = floor($offset);
$minute = floor(($offset - $hour) * 60);
if ($isPositive) {
$offset = sprintf('+%02d%02d', $hour, $minute);
} else {
$offset = sprintf('-%02d%02d', $hour, $minute);
}
return new \DateTimeZone($offset);
}
return new \DateTimeZone($timezone);
}
public function convertFrom(string|array|int|float|bool|null $raw, string $name): mixed
{
if ($raw === null && array_search('null', $this->types, true) !== false) {
return null;
}
if (!is_string($raw)) {
throw new \InvalidArgumentException("DateTimeConverter can not convert non-string: {$name}");
}
if (array_search('DateTimeImmutable', $this->types, true) !== false) {
$objDateTime = new \DateTimeImmutable($raw, $this->timeZoneOffset);
} else if (array_search('DateTime', $this->types, true) !== false) {
$objDateTime = new \DateTime($raw, $this->timeZoneOffset);
} else {
$objDateTime = new \DateTimeImmutable($raw, $this->timeZoneOffset);
}
if ($objDateTime->getTimezone() !== $this->timeZoneOffset) {
$objDateTime = $objDateTime->setTimezone($this->timeZoneOffset);
}
return $objDateTime;
}
public function convertTo(mixed $data): string|array|int|float|bool|null
{
if ($data === null && array_search('null', $this->types, true) !== false) {
return null;
}
if (!$data instanceof \DateTimeInterface) {
throw new \Exception('DateTimeConverter can not convert non-DateTimeInterface');
}
if ($data->getTimezone() !== $this->timeZoneOffset) {
$data = \DateTimeImmutable::createFromInterface($data)->setTimezone($this->timeZoneOffset);
}
return $data->format($this->datetimeFormat);
}
}
@@ -1,147 +0,0 @@
<?php
namespace sammo\DTO\Converter;
use sammo\DTO\DTO;
class DefaultConverter implements Converter
{
public function __construct(private array $types)
{
}
public static function convertFromItem(string $type, $raw, string $name, bool &$success): mixed
{
$success = false;
if (is_subclass_of($type, \UnitEnum::class)) {
$enumType = new \ReflectionEnum($type);
if ($enumType->isBacked()) {
$enum = $enumType->getMethod('tryFrom')->invoke(null, $raw);
if ($enum === null) {
return null;
}
$success = true;
return $enum;
}
if (!$enumType->hasCase($raw)) {
return null;
}
$success = true;
return $enumType->getCase($raw)->getValue();
}
if (is_subclass_of($type, DTO::class)) {
try {
$class = new \ReflectionClass($type);
$obj = $class->getMethod('fromArray')->invoke(null, $raw);
$success = true;
return $obj;
} catch (\Throwable) {
}
return null;
}
if ($type === 'array') {
if (!is_array($raw)) {
return null;
}
if (!array_is_list($raw)) {
throw new \Exception("value is not a array: $name");
}
foreach ($raw as $value) {
if (is_int($value) || is_float($value) || is_string($value)) {
continue;
}
if (is_bool($value) || is_null($value)) {
continue;
}
throw new \Exception("DefaultConverter can not convert array: $name");
}
$success = true;
return $raw;
}
if($type === 'int' && is_int($raw)){
$success = true;
return $raw;
}
if($type === 'float' && is_float($raw)){
$success = true;
return $raw;
}
if($type === 'string' && is_string($raw)){
$success = true;
return $raw;
}
if($type === 'bool'){
if(is_bool($raw)){
$success = true;
return $raw;
}
if($raw === 0 || $raw === 1){
$success = true;
return $raw !== 0;
}
}
return null;
}
public function convertFrom(string|array|int|float|bool|null $raw, string $name): mixed
{
if ($raw === null && array_search('null', $this->types, true) !== false) {
return null;
}
foreach ($this->types as $type) {
$success = false;
$value = self::convertFromItem($type, $raw, $name, $success);
if ($success) {
return $value;
}
}
throw new \Exception('DefaultConverter can not convert '.gettype($raw).": $name as ".join('|', $this->types));
}
public function convertTo(mixed $data): string|array|int|float|bool|null
{
if ($data === null) {
return $data;
}
if ($data instanceof \UnitEnum) {
if ($data instanceof \BackedEnum) {
return $data->value;
}
return $data->name;
}
if ($data instanceof DTO) {
return $data->toArray();
}
if (is_array($data)) {
if (!array_is_list($data)) {
throw new \Exception('value is not a array');
}
foreach ($data as $value) {
if (is_int($value) || is_float($value) || is_string($value)) {
continue;
}
if (is_bool($value) || is_null($value)) {
continue;
}
throw new \Exception('DefaultConverter can not convert array');
}
}
return $data;
}
}
-53
View File
@@ -1,53 +0,0 @@
<?php
namespace sammo\DTO\Converter;
class MapConverter implements Converter
{
private Converter $itemConverter;
public function __construct(private array $types, array $itemTypes, ?string $itemConverterClass = null, ...$args)
{
if(!is_array($itemTypes)){
throw new \Exception('itemTypes is not a array');
}
$itemConverterClass = array_shift($args);
if($itemConverterClass === null){
$itemConverterClass = DefaultConverter::class;
}
else if (!is_subclass_of($itemConverterClass, Converter::class)) {
throw new \Exception("$itemConverterClass is not a subclass of \sammo\DTO\Converter\Converter");
}
$this->itemConverter = new $itemConverterClass($itemTypes, ...$args);
}
public function convertFrom(string|array|int|float|bool|null $raw, string $name): mixed
{
if ($raw === null && array_search('null', $this->types, true) !== false) {
return null;
}
if (!is_array($raw)) {
throw new \Exception("value is not a array: $name");
}
$result = [];
foreach ($raw as $key => $value) {
$result[$key] = $this->itemConverter->convertFrom($value, $name);
}
return $result;
}
public function convertTo(mixed $data): string|array|int|float|bool|null
{
if ($data === null && array_search('null', $this->types, true) !== false) {
return null;
}
if (!is_array($data) && !($data instanceof \Traversable)) {
throw new \Exception('value is not a array');
}
$result = [];
foreach ($data as $key => $value) {
$result[$key] = $this->itemConverter->convertTo($value);
}
return $result;
}
}
-164
View File
@@ -1,164 +0,0 @@
<?php
namespace sammo\DTO;
use Ds\Set;
use sammo\DTO\Attr\Convert;
use sammo\DTO\Converter\DefaultConverter;
abstract class DTO
{
public static function fromArray(\ArrayAccess|array $array): static
{
$reflection = new \ReflectionClass(static::class);
if ($array instanceof \ArrayAccess) {
$keyExists = fn (string|int $key) => $array->offsetExists($key);
} else {
$keyExists = fn (string|int $key) => array_key_exists($key, $array);
}
$params = Util\DTOUtil::getConstructorParams($reflection);
$args = [];
$lazyMap = [];
foreach ($reflection->getProperties(
\ReflectionProperty::IS_PUBLIC
) as $property) {
$attrs = Util\DTOUtil::getAttrs($property);
$name = $property->getName();
$rawName = $name;
$param = $params[$name] ?? null;
if(key_exists(Attr\Ignore::class, $attrs)){
if($param !== null){
throw new \Exception("Property {$name} is ignored but has a constructor parameter");
}
continue;
}
if (key_exists(Attr\DefaultValueGenerator::class, $attrs)){
/** @var Attr\DefaultValueGenerator */
$defaultValueSetter = $attrs[Attr\DefaultValueGenerator::class]->newInstance();
} else if (key_exists(Attr\DefaultValue::class, $attrs)) {
/** @var Attr\DefaultValue */
$defaultValueSetter = $attrs[Attr\DefaultValue::class]->newInstance();
}
else{
$defaultValueSetter = null;
}
if (key_exists(Attr\RawName::class, $attrs)) {
$rawAttr = $attrs[Attr\RawName::class];
$attr = new Attr\RawName(...$rawAttr->getArguments());
$rawName = $attr->rawName;
}
if (!$keyExists($rawName)) {
if ($param !== null && $param->isOptional()){
$defaultValue = $param->getDefaultValue();
}
else if ($property->hasDefaultValue()) {
$defaultValue = $property->getDefaultValue();
} else if($defaultValueSetter !== null){
$defaultValue = $defaultValueSetter->getDefaultValue();
} else if ($property->getType()->allowsNull()) {
$defaultValue = null;
} else {
throw new \Exception("Missing property: {$name}");
}
if($param !== null){
$args[$name] = $defaultValue;
}
else{
$lazyMap[$name] = $defaultValue;
}
continue;
}
$value = $array[$rawName];
if (key_exists(Attr\JsonString::class, $attrs)) {
$rawAttr = $attrs[Attr\JsonString::class];
$attr = new Attr\JsonString(...$rawAttr->getArguments());
$value = json_decode($value, true);
}
$propTypes = Util\DTOUtil::getPropTypes($property);
if (key_exists(Attr\Convert::class, $attrs)) {
$rawAttr = $attrs[Attr\Convert::class];
$converter = new Convert(...$rawAttr->getArguments());
} else {
$converter = new Convert(DefaultConverter::class);
}
$value = $converter->setType($propTypes)->convertFrom($value, $name);
if($param !== null){
$args[$name] = $value;
}
else{
$lazyMap[$name] = $value;
}
}
$object = $reflection->newInstanceArgs($args);
foreach($lazyMap as $name => $value){
$object->{$name} = $value;
}
return $object;
}
public function toArray(string ...$exceptKeys): array
{
$reflection = new \ReflectionClass($this::class);
$result = [];
$exceptKeySet = new Set($exceptKeys);
foreach ($reflection->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
$value = $property->getValue($this);
$attrs = Util\DTOUtil::getAttrs($property);
$name = $property->getName();
if(key_exists(Attr\Ignore::class, $attrs)){
continue;
}
if($exceptKeySet->contains($name)){
continue;
}
if (key_exists(Attr\RawName::class, $attrs)) {
$rawAttr = $attrs[Attr\RawName::class];
$attr = new Attr\RawName(...$rawAttr->getArguments());
$name = $attr->rawName;
}
$propTypes = Util\DTOUtil::getPropTypes($property);
if (key_exists(Attr\Convert::class, $attrs)) {
$converter = new Convert(...$attrs[Attr\Convert::class]->getArguments());
} else {
$converter = new Convert(DefaultConverter::class);
}
$value = $converter->setType($propTypes)->convertTo($value);
if (key_exists(Attr\JsonString::class, $attrs)) {
$rawAttr = $attrs[Attr\JsonString::class];
$attr = new Attr\JsonString(...$rawAttr->getArguments());
if($value === [] && $attr->emptyItemIsArray){
$value = (object)null;
}
$value = json_encode($value, $attr->jsonFlag);
}
if ($value === null && key_exists(Attr\NullIsUndefined::class, $attrs)) {
continue;
}
$result[$name] = $value;
}
return $result;
}
}
-68
View File
@@ -1,68 +0,0 @@
<?php
namespace sammo\DTO\Util;
class DTOUtil{
private function __construct()
{
}
/**
* @return array<string,\ReflectionAttribute>
*/
public static function getAttrs(\ReflectionProperty $prop): array{
$result = [];
foreach($prop->getAttributes() as $attr){
$result[$attr->getName()] = $attr;
}
return $result;
}
/**
* @return array<string,\ReflectionParameter>
*/
public static function getConstructorParams(\ReflectionClass $class): array{
$constructor = $class->getConstructor();
if($constructor === null){
return [];
}
$result = [];
foreach($constructor->getParameters() as $param){
$result[$param->getName()] = $param;
}
return $result;
}
/**
* @return array<string>
*/
public static function getPropTypes(\ReflectionProperty $prop): array{
$result = [];
$type = $prop->getType();
if($type === null){
throw new \Exception("Property {$prop->getName()} has no type");
}
if($type->allowsNull()){
$result[] = 'null';
}
if($type instanceof \ReflectionIntersectionType){
throw new \Exception("Intersection types are not supported");
}
if($type instanceof \ReflectionNamedType){
$result[] = $type->getName();
return $result;
}
if($type instanceof \ReflectionUnionType){
foreach($type->getTypes() as $type){
$result[] = $type->getName();
}
return $result;
}
throw new \sammo\MustNotBeReachedException;
}
}