Compare commits
13 Commits
Author | SHA1 | Date | |
---|---|---|---|
4313b361e4 | |||
5ee9eddb08 | |||
6166de2fb7 | |||
fc09440e24 | |||
ca1b291fd0 | |||
988a4a01d1 | |||
43bc10d24f | |||
c16d2e7e61 | |||
e3290afe79 | |||
eb128bda28 | |||
88303bb058 | |||
20317698e9 | |||
77c0c14c14 |
@ -8,7 +8,9 @@
|
||||
"ext-iconv": "*",
|
||||
"ext-json": "*",
|
||||
"symfony/string": "^5.3",
|
||||
"rinsvent/attribute-extractor": "^0.0"
|
||||
"rinsvent/attribute-extractor": "^0.0",
|
||||
"rinsvent/transformer": "^0.0",
|
||||
"symfony/property-access": "^6.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"codeception/codeception": "^4.1",
|
||||
|
@ -1,13 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Rinsvent\DTO2Data\Attribute;
|
||||
|
||||
#[\Attribute(\Attribute::TARGET_ALL|\Attribute::IS_REPEATABLE)]
|
||||
class DataPath
|
||||
{
|
||||
public function __construct(
|
||||
public string $path,
|
||||
/** @var string[] $tags */
|
||||
public array $tags = ['default']
|
||||
) {}
|
||||
}
|
@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Rinsvent\DTO2Data\Attribute;
|
||||
|
||||
#[\Attribute(\Attribute::TARGET_ALL|\Attribute::IS_REPEATABLE)]
|
||||
class HandleTags
|
||||
{
|
||||
public function __construct(
|
||||
public string $method,
|
||||
) {}
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rinsvent\DTO2Data\Attribute;
|
||||
|
||||
@ -9,5 +10,6 @@ class PropertyPath
|
||||
public string $path,
|
||||
/** @var string[] $tags */
|
||||
public array $tags = ['default']
|
||||
) {}
|
||||
}
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
@ -1,17 +1,25 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rinsvent\DTO2Data\Attribute;
|
||||
|
||||
#[\Attribute(\Attribute::TARGET_ALL|\Attribute::IS_REPEATABLE)]
|
||||
class Schema
|
||||
{
|
||||
public ?array $baseMap = null;
|
||||
protected array $baseMap = [];
|
||||
|
||||
public function __construct(
|
||||
public ?array $map = null,
|
||||
/** @var string[] $tags */
|
||||
public array $tags = ['default']
|
||||
public array $map = [],
|
||||
) {
|
||||
$this->map = $map ?? $this->baseMap;
|
||||
}
|
||||
|
||||
public function getMap(): array
|
||||
{
|
||||
return $this->baseMap ?: $this->map;
|
||||
}
|
||||
|
||||
public function getTags(mixed $data = null): array
|
||||
{
|
||||
return ['default'];
|
||||
}
|
||||
}
|
||||
|
@ -1,342 +1,168 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rinsvent\DTO2Data;
|
||||
|
||||
use ReflectionMethod;
|
||||
use ReflectionProperty;
|
||||
use Rinsvent\AttributeExtractor\ClassExtractor;
|
||||
use Rinsvent\AttributeExtractor\MethodExtractor;
|
||||
use Rinsvent\AttributeExtractor\PropertyExtractor;
|
||||
use Rinsvent\DTO2Data\Attribute\DataPath;
|
||||
use Rinsvent\DTO2Data\Attribute\HandleTags;
|
||||
use Rinsvent\DTO2Data\Attribute\PropertyPath;
|
||||
use Rinsvent\DTO2Data\Attribute\Schema;
|
||||
use Rinsvent\DTO2Data\Resolver\TransformerResolverStorage;
|
||||
use Rinsvent\DTO2Data\Transformer\Meta;
|
||||
use Rinsvent\DTO2Data\Transformer\TransformerInterface;
|
||||
use Rinsvent\Transformer\Transformer;
|
||||
use Rinsvent\Transformer\Transformer\Meta;
|
||||
use Symfony\Component\PropertyAccess\PropertyAccess;
|
||||
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
|
||||
|
||||
class Dto2DataConverter
|
||||
{
|
||||
public function getTags(object $object, array $tags = []): array
|
||||
private PropertyAccessorInterface $propertyAccessor;
|
||||
private Transformer $transformer;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
return $this->processTags($object, $tags);
|
||||
$this->propertyAccessor = PropertyAccess::createPropertyAccessorBuilder()
|
||||
->disableExceptionOnInvalidPropertyPath()
|
||||
->enableMagicMethods()
|
||||
->getPropertyAccessor();
|
||||
$this->transformer = new Transformer();
|
||||
}
|
||||
|
||||
public function convert(object $object, array $tags = []): array
|
||||
public function convert($data, string $schemaClass): array
|
||||
{
|
||||
$tags = empty($tags) ? ['default'] : $tags;
|
||||
$schema = $this->grabSchema($object, $tags);
|
||||
return $this->convertObjectByMap($object, $schema->map, $tags);
|
||||
}
|
||||
|
||||
public function convertObjectByMap(object $object, array $map, array $tags = []): array
|
||||
{
|
||||
$data = [];
|
||||
|
||||
$reflectionObject = new \ReflectionObject($object);
|
||||
foreach ($map as $key => $propertyInfo) {
|
||||
$sourceName = is_array($propertyInfo) ? $key : $propertyInfo;
|
||||
|
||||
if (!method_exists($object, $sourceName) && !property_exists($object, $sourceName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = $this->grabValue($object, $sourceName, $tags);
|
||||
|
||||
// Если нет карты, то не сериализуем.
|
||||
if (is_object($value) && is_array($propertyInfo)) {
|
||||
$value = $this->convertObjectByMap($value, $propertyInfo, $tags);
|
||||
} elseif (is_iterable($value)) {
|
||||
$childMap = is_array($propertyInfo) ? $propertyInfo : null;
|
||||
$value = $this->convertArrayByMap($value, $childMap, $tags);
|
||||
} elseif (!is_scalar($value) && null !== $value) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->processIterationTransformers($object, $sourceName, $value, $tags);
|
||||
$dataPath = $this->grabIterationDataPath($object, $sourceName, $tags);
|
||||
$data[$dataPath] = $value;
|
||||
$schema = new $schemaClass();
|
||||
if (!$schema instanceof Schema) {
|
||||
throw new \InvalidArgumentException(
|
||||
'Schema should be instance of Rinsvent\DTO2Data\Attribute\Schema'
|
||||
);
|
||||
}
|
||||
|
||||
$this->processClassTransformers($reflectionObject, $data, $tags);
|
||||
|
||||
return $data;
|
||||
return $this->convertByMap($data, $schema->getMap(), $schema->getTags($data));
|
||||
}
|
||||
|
||||
public function convertArrayByMap($data, ?array $map, array $tags = []): ?array
|
||||
private function convertByMap($data, array $map, array $tags): array
|
||||
{
|
||||
$isAssociative = count($data) && !array_key_exists(0, $data);
|
||||
|
||||
$tempValue = [];
|
||||
foreach ($data as $key => $item) {
|
||||
if (is_scalar($item)) {
|
||||
$tempValue[$key] = $item;
|
||||
continue;
|
||||
}
|
||||
if (is_iterable($item) && $map) {
|
||||
$tempValue[$key] = $this->convertArrayByMap($item, $map, $tags);
|
||||
continue;
|
||||
}
|
||||
if (is_object($item) && $map) {
|
||||
$tempValue[$key] = $this->convertObjectByMap($item, $map, $tags);
|
||||
continue;
|
||||
$result = [];
|
||||
if (is_iterable($data)) {
|
||||
foreach ($data as $item) {
|
||||
$result[] = $this->processItem($item, $map, $tags);
|
||||
}
|
||||
} else {
|
||||
$result = $this->processItem($data, $map, $tags);
|
||||
}
|
||||
return $tempValue;
|
||||
return $result;
|
||||
}
|
||||
|
||||
protected function grabValue(object $object, $sourceName, array $tags)
|
||||
private function processItem($data, array $map, array $tags): array
|
||||
{
|
||||
if (method_exists($object, $sourceName)) {
|
||||
$reflectionSource = new ReflectionMethod($object, $sourceName);
|
||||
return $this->getMethodValue($object, $reflectionSource);
|
||||
} elseif (property_exists($object, $sourceName)) {
|
||||
$reflectionSource = new ReflectionProperty($object, $sourceName);
|
||||
$propertyExtractor = new PropertyExtractor($object::class, $sourceName);
|
||||
/** @var PropertyPath $propertyPath */
|
||||
while ($propertyPath = $propertyExtractor->fetch(PropertyPath::class)) {
|
||||
$filteredTags = array_diff($tags, $propertyPath->tags);
|
||||
if (count($filteredTags) === count($tags)) {
|
||||
continue;
|
||||
$result = [];
|
||||
foreach ($map as $key => $item) {
|
||||
try {
|
||||
switch (true) {
|
||||
// key -> propertyPath (===).
|
||||
case is_int($key) && is_string($item):
|
||||
$result[$item] = $this->grabValue($data, $item);
|
||||
$result[$item] = $this->transform($data, $item, $result[$item], $tags);
|
||||
break;
|
||||
// key -> propertyPath (!==)
|
||||
case is_string($key) && is_string($item):
|
||||
$result[$key] = $this->grabValue($data, $item);
|
||||
$result[$key] = $this->transform($data, $item, $result[$key], $tags);
|
||||
break;
|
||||
// key -> recursive data processing
|
||||
case is_string($key) && is_array($item):
|
||||
$result[$key] = $this->convertByMap($this->grabValue($data, $key), $item, $tags);
|
||||
break;
|
||||
// key -> virtual field
|
||||
case is_string($key) && is_callable($item):
|
||||
$result[$key] = call_user_func_array($item, [$data]);
|
||||
break;
|
||||
// key -> data processing with transformer
|
||||
case $item instanceof Meta:
|
||||
case (new $item) instanceof Meta:
|
||||
$meta = is_string($item) ? new $item : $item;
|
||||
$result[$key] = $this->transformer->transform($data, $meta);
|
||||
break;
|
||||
// key -> recursive data processing with other schema
|
||||
case $item instanceof Schema:
|
||||
case (new $item) instanceof Schema:
|
||||
$schemaClass = is_object($item) ? $item::class : $item;
|
||||
$result[$key] = $this->convert($data[$key] ?? null, $schemaClass);
|
||||
break;
|
||||
default:
|
||||
$result[$key] = null;
|
||||
}
|
||||
return $this->getValueByPath($object, $propertyPath->path);
|
||||
}
|
||||
return $this->getValue($object, $reflectionSource);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function processIterationTransformers(object $object, string $sourceName, &$value, array $tags): void
|
||||
{
|
||||
if (method_exists($object, $sourceName)) {
|
||||
$reflectionSource = new ReflectionMethod($object, $sourceName);
|
||||
$this->processMethodTransformers($reflectionSource, $value, $tags);
|
||||
} elseif (property_exists($object, $sourceName)) {
|
||||
$reflectionSource = new ReflectionProperty($object, $sourceName);
|
||||
$this->processTransformers($reflectionSource, $value, $tags);
|
||||
}
|
||||
}
|
||||
|
||||
public function grabIterationDataPath(object $object, string $sourceName, array $tags): string
|
||||
{
|
||||
if (method_exists($object, $sourceName)) {
|
||||
$reflectionSource = new ReflectionMethod($object, $sourceName);
|
||||
$dataPath = $this->grabMethodDataPath($reflectionSource, $tags);
|
||||
} elseif (property_exists($object, $sourceName)) {
|
||||
$reflectionSource = new ReflectionProperty($object, $sourceName);
|
||||
$dataPath = $this->grabDataPath($reflectionSource, $tags);
|
||||
}
|
||||
return $dataPath ?? $sourceName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получаем теги для обработки
|
||||
*/
|
||||
protected function processTags(object $object, array $tags): array
|
||||
{
|
||||
$classExtractor = new ClassExtractor($object::class);
|
||||
/** @var HandleTags $tagsMeta */
|
||||
if ($tagsMeta = $classExtractor->fetch(HandleTags::class)) {
|
||||
if (method_exists($object, $tagsMeta->method)) {
|
||||
$reflectionMethod = new ReflectionMethod($object, $tagsMeta->method);
|
||||
if (!$reflectionMethod->isPublic()) {
|
||||
$reflectionMethod->setAccessible(true);
|
||||
}
|
||||
$methodTags = $reflectionMethod->invoke($object, ...[$tags]);
|
||||
if (!$reflectionMethod->isPublic()) {
|
||||
$reflectionMethod->setAccessible(false);
|
||||
}
|
||||
return $methodTags;
|
||||
} catch (\Throwable) {
|
||||
$result[$key] = null;
|
||||
}
|
||||
}
|
||||
|
||||
return $tags;
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Трнансформируем на уровне класса
|
||||
*/
|
||||
protected function processClassTransformers(\ReflectionObject $object, &$data, array $tags): void
|
||||
private function transform(object|array|null $data, string $path, mixed $value, array $tags): mixed
|
||||
{
|
||||
$className = $object->getName();
|
||||
$classExtractor = new ClassExtractor($className);
|
||||
/** @var Meta $transformMeta */
|
||||
while ($transformMeta = $classExtractor->fetch(Meta::class)) {
|
||||
$transformMeta->returnType = $className;
|
||||
$filteredTags = array_diff($tags, $transformMeta->tags);
|
||||
if (count($filteredTags) === count($tags)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$transformer = $this->grabTransformer($transformMeta);
|
||||
$transformer->transform($data, $transformMeta);
|
||||
$metas = $this->grabTransformMetas($data, $path);
|
||||
foreach ($metas as $meta) {
|
||||
$value = $this->transformer->transform($value, $meta, $tags);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Трнансформируем на уровне свойст объекта
|
||||
*/
|
||||
protected function processTransformers(\ReflectionProperty $property, &$data, array $tags): void
|
||||
private function grabValue(object|array|null $value, string $path): mixed
|
||||
{
|
||||
$propertyName = $property->getName();
|
||||
$propertyExtractor = new PropertyExtractor($property->class, $propertyName);
|
||||
/** @var Meta $transformMeta */
|
||||
while ($transformMeta = $propertyExtractor->fetch(Meta::class)) {
|
||||
$filteredTags = array_diff($tags, $transformMeta->tags);
|
||||
if (count($filteredTags) === count($tags)) {
|
||||
continue;
|
||||
}
|
||||
/** @var \ReflectionNamedType $reflectionPropertyType */
|
||||
$reflectionPropertyType = $property->getType();
|
||||
$propertyType = $reflectionPropertyType->getName();
|
||||
$transformMeta->returnType = $propertyType;
|
||||
$transformMeta->allowsNull = $reflectionPropertyType->allowsNull();
|
||||
$transformer = $this->grabTransformer($transformMeta);
|
||||
$transformer->transform($data, $transformMeta);
|
||||
}
|
||||
}
|
||||
|
||||
protected function processMethodTransformers(ReflectionMethod $method, &$data, array $tags): void
|
||||
{
|
||||
$methodName = $method->getName();
|
||||
$methodExtractor = new MethodExtractor($method->class, $methodName);
|
||||
/** @var Meta $transformMeta */
|
||||
while ($transformMeta = $methodExtractor->fetch(Meta::class)) {
|
||||
$filteredTags = array_diff($tags, $transformMeta->tags);
|
||||
if (count($filteredTags) === count($tags)) {
|
||||
continue;
|
||||
}
|
||||
/** @var \ReflectionNamedType $reflectionMethodType */
|
||||
$reflectionMethodType = $method->getReturnType();
|
||||
$methodType = $reflectionMethodType->getName();
|
||||
$transformMeta->returnType = $methodType;
|
||||
$transformMeta->allowsNull = $reflectionMethodType->allowsNull();
|
||||
$transformer = $this->grabTransformer($transformMeta);
|
||||
$transformer->transform($data, $transformMeta);
|
||||
}
|
||||
}
|
||||
|
||||
protected function grabTransformer(Meta $meta): TransformerInterface
|
||||
{
|
||||
$storage = TransformerResolverStorage::getInstance();
|
||||
$resolver = $storage->get($meta::TYPE);
|
||||
return $resolver->resolve($meta);
|
||||
}
|
||||
|
||||
private function getValueByPath($data, string $path)
|
||||
{
|
||||
$parts = explode('.', $path);
|
||||
$length = count($parts);
|
||||
$i = 1;
|
||||
foreach ($parts as $part) {
|
||||
// Если получили скалярное значение но прошли не весь путь, то вернем null
|
||||
if (is_scalar($data) && $i < $length) {
|
||||
return null;
|
||||
}
|
||||
// Если объекс реализует ArrayAccess, то получаем значение и идем дальше
|
||||
if (is_object($data) && $data instanceof \ArrayAccess) {
|
||||
$data = $data[$part] ?? null;
|
||||
continue;
|
||||
}
|
||||
// Если объект, то достаем значение
|
||||
if (is_object($data)) {
|
||||
if (!property_exists($data, $part)) {
|
||||
return null;
|
||||
}
|
||||
$property = new ReflectionProperty($data, $part);
|
||||
$data = $this->getValue($data, $property);
|
||||
continue;
|
||||
}
|
||||
// Если массив, то достаем занчение и идем дальше
|
||||
if (is_array($data)) {
|
||||
$data = $data[$part] ?? null;
|
||||
continue;
|
||||
}
|
||||
$i++;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function getValue(object $object, \ReflectionProperty $property)
|
||||
{
|
||||
if (!$property->isPublic()) {
|
||||
$property->setAccessible(true);
|
||||
}
|
||||
|
||||
if (!$property->isInitialized($object)) {
|
||||
if (null === $value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$value = $property->getValue($object);
|
||||
|
||||
if (!$property->isPublic()) {
|
||||
$property->setAccessible(false);
|
||||
}
|
||||
|
||||
return $value;
|
||||
$path = is_array($value) && 0 === mb_substr_count($path, '.') &&
|
||||
false === mb_strpos($path, '[')
|
||||
? "[{$path}]"
|
||||
: $path;
|
||||
return $this->propertyAccessor->getValue($value, $path);
|
||||
}
|
||||
|
||||
private function getMethodValue(object $object, ReflectionMethod $method)
|
||||
/**
|
||||
* @return Meta[]
|
||||
*/
|
||||
private function grabTransformMetas(mixed $data, string $propertyPath): array
|
||||
{
|
||||
if (!$method->isPublic()) {
|
||||
$method->setAccessible(true);
|
||||
}
|
||||
|
||||
$value = $method->invoke($object);
|
||||
|
||||
if (!$method->isPublic()) {
|
||||
$method->setAccessible(false);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
private function grabSchema(object $object, array $tags): ?Schema
|
||||
{
|
||||
$classExtractor = new ClassExtractor($object::class);
|
||||
/** @var Schema $schema */
|
||||
while ($schema = $classExtractor->fetch(Schema::class)) {
|
||||
$filteredTags = array_diff($tags, $schema->tags);
|
||||
if (count($filteredTags) === count($tags)) {
|
||||
continue;
|
||||
$result = [];
|
||||
$propertyName = $propertyPath;
|
||||
$propertyPathParts = explode('.', $propertyPath);
|
||||
if (count($propertyPathParts) > 1) {
|
||||
$propertyName = array_shift($propertyPathParts);
|
||||
$pathToObject = implode('.', $propertyPathParts);
|
||||
$object = $this->grabValue($data, $pathToObject);
|
||||
if (!is_object($object)) {
|
||||
return [];
|
||||
}
|
||||
return $schema;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
if (!is_object($data)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
private function grabDataPath(\ReflectionProperty $property, array $tags): ?string
|
||||
{
|
||||
$propertyName = $property->getName();
|
||||
$propertyExtractor = new PropertyExtractor($property->class, $propertyName);
|
||||
/** @var DataPath $schema */
|
||||
while ($dataPath = $propertyExtractor->fetch(DataPath::class)) {
|
||||
$filteredTags = array_diff($tags, $dataPath->tags);
|
||||
if (count($filteredTags) === count($tags)) {
|
||||
continue;
|
||||
if (property_exists($data, $propertyName)) {
|
||||
$reflectionProperty = new ReflectionProperty($data, $propertyName);
|
||||
$methodExtractor = new PropertyExtractor($reflectionProperty->class, $propertyName);
|
||||
while ($meta = $methodExtractor->fetch(Meta::class)) {
|
||||
$result[] = $meta;
|
||||
}
|
||||
return $dataPath->path;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function grabMethodDataPath(ReflectionMethod $method, array $tags): ?string
|
||||
{
|
||||
$methodName = $method->getName();
|
||||
$methodExtractor = new MethodExtractor($method->class, $methodName);
|
||||
/** @var DataPath $schema */
|
||||
while ($dataPath = $methodExtractor->fetch(DataPath::class)) {
|
||||
$filteredTags = array_diff($tags, $dataPath->tags);
|
||||
if (count($filteredTags) === count($tags)) {
|
||||
continue;
|
||||
if ($result) {
|
||||
return $result;
|
||||
}
|
||||
return $dataPath->path;
|
||||
}
|
||||
|
||||
return null;
|
||||
foreach (['get', 'has', 'is'] as $prefix) {
|
||||
$methodName = $prefix . ucfirst($propertyName);
|
||||
if (method_exists($data, $methodName)) {
|
||||
$reflectionMethod = new \ReflectionMethod($data, $methodName);
|
||||
$methodExtractor = new MethodExtractor($reflectionMethod->class, $methodName);
|
||||
while ($meta = $methodExtractor->fetch(Meta::class)) {
|
||||
$result[] = $meta;
|
||||
}
|
||||
}
|
||||
if ($result) {
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
@ -1,16 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Rinsvent\DTO2Data\Resolver;
|
||||
|
||||
use Rinsvent\DTO2Data\Transformer\Meta;
|
||||
use Rinsvent\DTO2Data\Transformer\TransformerInterface;
|
||||
|
||||
class SimpleResolver implements TransformerResolverInterface
|
||||
{
|
||||
public function resolve(Meta $meta): TransformerInterface
|
||||
{
|
||||
$metaClass = $meta::class;
|
||||
$transformerClass = $metaClass . 'Transformer';
|
||||
return new $transformerClass;
|
||||
}
|
||||
}
|
@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Rinsvent\DTO2Data\Resolver;
|
||||
|
||||
use Rinsvent\DTO2Data\Transformer\Meta;
|
||||
use Rinsvent\DTO2Data\Transformer\TransformerInterface;
|
||||
|
||||
interface TransformerResolverInterface
|
||||
{
|
||||
public function resolve(Meta $meta): TransformerInterface;
|
||||
}
|
@ -1,32 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Rinsvent\DTO2Data\Resolver;
|
||||
|
||||
class TransformerResolverStorage
|
||||
{
|
||||
private array $items = [];
|
||||
|
||||
public static function getInstance(): self
|
||||
{
|
||||
static $instance = null;
|
||||
|
||||
if ($instance) {
|
||||
return $instance;
|
||||
}
|
||||
|
||||
$instance = new self();
|
||||
$instance->add('simple', new SimpleResolver());
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
public function add(string $code, TransformerResolverInterface $transformerResolver): void
|
||||
{
|
||||
$this->items[$code] = $transformerResolver;
|
||||
}
|
||||
|
||||
public function get(string $code): TransformerResolverInterface
|
||||
{
|
||||
return $this->items[$code];
|
||||
}
|
||||
}
|
@ -1,15 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Rinsvent\DTO2Data\Transformer;
|
||||
|
||||
#[\Attribute(\Attribute::TARGET_ALL|\Attribute::IS_REPEATABLE)]
|
||||
abstract class Meta
|
||||
{
|
||||
public const TYPE = 'simple';
|
||||
public ?string $returnType = null;
|
||||
public ?bool $allowsNull = null;
|
||||
|
||||
public function __construct(
|
||||
public array $tags = ['default']
|
||||
) {}
|
||||
}
|
@ -1,8 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Rinsvent\DTO2Data\Transformer;
|
||||
|
||||
interface TransformerInterface
|
||||
{
|
||||
public function transform(&$data, Meta $meta): void;
|
||||
}
|
@ -1,14 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Rinsvent\DTO2Data\Transformer;
|
||||
|
||||
#[\Attribute(\Attribute::TARGET_ALL|\Attribute::IS_REPEATABLE)]
|
||||
class Trim extends Meta
|
||||
{
|
||||
public function __construct(
|
||||
public array $tags = ['default'],
|
||||
public string $characters = " \t\n\r\0\x0B"
|
||||
) {
|
||||
parent::__construct(...func_get_args());
|
||||
}
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Rinsvent\DTO2Data\Transformer;
|
||||
|
||||
class TrimTransformer implements TransformerInterface
|
||||
{
|
||||
/**
|
||||
* @param string|null $data
|
||||
* @param Trim $meta
|
||||
*/
|
||||
public function transform(&$data, Meta $meta): void
|
||||
{
|
||||
if ($data === null) {
|
||||
return;
|
||||
}
|
||||
$data = trim($data, $meta->characters);
|
||||
}
|
||||
}
|
@ -6,7 +6,10 @@ use Rinsvent\DTO2Data\Dto2DataConverter;
|
||||
use Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest\Author;
|
||||
use Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest\Bar;
|
||||
use Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest\BuyRequest;
|
||||
use Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest\Collection;
|
||||
use Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest\CollectionItem;
|
||||
use Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest\HelloRequest;
|
||||
use Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest\HelloSchema;
|
||||
use Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest\UUID;
|
||||
|
||||
class FillTest extends \Codeception\Test\Unit
|
||||
@ -16,14 +19,6 @@ class FillTest extends \Codeception\Test\Unit
|
||||
*/
|
||||
protected $tester;
|
||||
|
||||
protected function _before()
|
||||
{
|
||||
}
|
||||
|
||||
protected function _after()
|
||||
{
|
||||
}
|
||||
|
||||
// tests
|
||||
public function testSuccessFillRequestData()
|
||||
{
|
||||
@ -69,8 +64,51 @@ class FillTest extends \Codeception\Test\Unit
|
||||
$bar->barField = 32;
|
||||
$helloRequest->bar = $bar;
|
||||
$helloRequest->uuid = new UUID('qwerqw-qwerqwe-werqw-qwerqw');
|
||||
$collection = new Collection();
|
||||
$collection->items = [
|
||||
new CollectionItem('3'),
|
||||
new CollectionItem('1'),
|
||||
new CollectionItem('2'),
|
||||
];
|
||||
$helloRequest->collection = $collection;
|
||||
$helloRequest->createdAt = new \DateTimeImmutable('2020-05-21 13:36:22');
|
||||
|
||||
$dto = $dto2DataConverter->convert($helloRequest);
|
||||
// private
|
||||
$helloRequest->setPsurname(' asdf');
|
||||
$helloRequest->setPage(3);
|
||||
$helloRequest->setPemails([
|
||||
'sfdgsa',
|
||||
'af234f',
|
||||
'asdf33333'
|
||||
]);
|
||||
$helloRequest->setPauthors([
|
||||
$author1,
|
||||
$author2
|
||||
]);
|
||||
$helloRequest->setPauthors2([
|
||||
[
|
||||
"name" => "Tolkien"
|
||||
],
|
||||
[
|
||||
"name" => "Sapkovsky"
|
||||
]
|
||||
]);
|
||||
$helloRequest->setPauthors3([
|
||||
[
|
||||
"name" => "Tolkien"
|
||||
],
|
||||
[
|
||||
"name" => "Sapkovsky"
|
||||
]
|
||||
]);
|
||||
$helloRequest->setPbuy($buy);
|
||||
$helloRequest->setPbar($bar);
|
||||
$helloRequest->setPuuid(new UUID('qwerqw-qwerqwe-werqw-qwerqw'));
|
||||
$helloRequest->setPcollection($collection);
|
||||
$helloRequest->setPcreatedAt(new \DateTimeImmutable('2020-05-21 13:36:22'));
|
||||
|
||||
|
||||
$dto = $dto2DataConverter->convert($helloRequest, HelloSchema::class);
|
||||
// codecept_debug(json_encode($dto));
|
||||
|
||||
$this->assertEquals([
|
||||
@ -97,7 +135,14 @@ class FillTest extends \Codeception\Test\Unit
|
||||
"name" => "Sapkovsky"
|
||||
]
|
||||
],
|
||||
"authors3" => [],
|
||||
"authors3" => [
|
||||
[
|
||||
"name" => "Tolkien"
|
||||
],
|
||||
[
|
||||
"name" => "Sapkovsky"
|
||||
]
|
||||
],
|
||||
"buy" => [
|
||||
"phrase" => "Buy buy!!!",
|
||||
"length" => 10,
|
||||
@ -106,7 +151,74 @@ class FillTest extends \Codeception\Test\Unit
|
||||
"bar" => [
|
||||
"barField" => 32
|
||||
],
|
||||
'uuid' => 'qwerqw-qwerqwe-werqw-qwerqw'
|
||||
'uuid' => 'qwerqw-qwerqwe-werqw-qwerqw',
|
||||
'collection' => [
|
||||
[
|
||||
'value' => '3',
|
||||
],
|
||||
[
|
||||
'value' => '1',
|
||||
],
|
||||
[
|
||||
'value' => '2',
|
||||
],
|
||||
],
|
||||
'createdAt' => '2020-05-21T13:36:22+00:00',
|
||||
|
||||
"psurname" => "asdf",
|
||||
"pfake_age" => 3,
|
||||
"pemails" => [
|
||||
"sfdgsa",
|
||||
"af234f",
|
||||
"asdf33333"
|
||||
],
|
||||
"pauthors" => [
|
||||
[
|
||||
"name" => "Tolkien"
|
||||
],
|
||||
[
|
||||
"name" => "Sapkovsky"
|
||||
]
|
||||
],
|
||||
"pauthors2" => [
|
||||
[
|
||||
"name" => "Tolkien"
|
||||
],
|
||||
[
|
||||
"name" => "Sapkovsky"
|
||||
]
|
||||
],
|
||||
"pauthors3" => [
|
||||
[
|
||||
"name" => "Tolkien"
|
||||
],
|
||||
[
|
||||
"name" => "Sapkovsky"
|
||||
]
|
||||
],
|
||||
"pbuy" => [
|
||||
"phrase" => "Buy buy!!!",
|
||||
"length" => 10,
|
||||
"isFirst" => true
|
||||
],
|
||||
"pbar" => [
|
||||
"barField" => 32
|
||||
],
|
||||
'puuid' => 'qwerqw-qwerqwe-werqw-qwerqw',
|
||||
'pcollection' => [
|
||||
[
|
||||
'value' => '3',
|
||||
],
|
||||
[
|
||||
'value' => '1',
|
||||
],
|
||||
[
|
||||
'value' => '2',
|
||||
],
|
||||
],
|
||||
'pcreatedAt' => '2020-05-21T13:36:22+00:00',
|
||||
|
||||
'fake_Pdevdo' => 'getPdevdo',
|
||||
], $dto);
|
||||
}
|
||||
}
|
||||
|
@ -1,39 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Rinsvent\DTO2Data\Tests\Converter;
|
||||
|
||||
use Rinsvent\DTO2Data\Dto2DataConverter;
|
||||
use Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest\HelloTagsRequest;
|
||||
|
||||
class TagsTest extends \Codeception\Test\Unit
|
||||
{
|
||||
/**
|
||||
* @var \UnitTester
|
||||
*/
|
||||
protected $tester;
|
||||
|
||||
protected function _before()
|
||||
{
|
||||
}
|
||||
|
||||
protected function _after()
|
||||
{
|
||||
}
|
||||
|
||||
// tests
|
||||
public function testSuccessFillRequestData()
|
||||
{
|
||||
$dto2DataConverter = new Dto2DataConverter();
|
||||
|
||||
$helloTagsRequest = new HelloTagsRequest();
|
||||
$helloTagsRequest->surname = ' Surname1234';
|
||||
$helloTagsRequest->age = 3;
|
||||
$helloTagsRequest->emails = [
|
||||
'sfdgsa',
|
||||
'af234f',
|
||||
'asdf33333'
|
||||
];
|
||||
$tags = $dto2DataConverter->getTags($helloTagsRequest);
|
||||
$this->assertEquals(['surname-group'], $tags);
|
||||
}
|
||||
}
|
34
tests/unit/Converter/fixtures/FillTest/Collection.php
Normal file
34
tests/unit/Converter/fixtures/FillTest/Collection.php
Normal file
@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest;
|
||||
|
||||
class Collection implements \Iterator
|
||||
{
|
||||
public array $items = [];
|
||||
private $position = 0;
|
||||
|
||||
public function rewind()
|
||||
{
|
||||
$this->position = 0;
|
||||
}
|
||||
|
||||
public function current()
|
||||
{
|
||||
return $this->items[$this->position];
|
||||
}
|
||||
|
||||
public function key()
|
||||
{
|
||||
return $this->position;
|
||||
}
|
||||
|
||||
public function next()
|
||||
{
|
||||
++$this->position;
|
||||
}
|
||||
|
||||
public function valid()
|
||||
{
|
||||
return isset($this->items[$this->position]);
|
||||
}
|
||||
}
|
13
tests/unit/Converter/fixtures/FillTest/CollectionItem.php
Normal file
13
tests/unit/Converter/fixtures/FillTest/CollectionItem.php
Normal file
@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest;
|
||||
|
||||
class CollectionItem
|
||||
{
|
||||
public string $value;
|
||||
|
||||
public function __construct(string $value)
|
||||
{
|
||||
$this->value = $value;
|
||||
}
|
||||
}
|
@ -2,16 +2,16 @@
|
||||
|
||||
namespace Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest;
|
||||
|
||||
use Rinsvent\DTO2Data\Attribute\DataPath;
|
||||
use Rinsvent\DTO2Data\Attribute\PropertyPath;
|
||||
use Rinsvent\DTO2Data\Transformer\Trim;
|
||||
use Rinsvent\Transformer\Transformer\DateTimeFormat;
|
||||
use Rinsvent\Transformer\Transformer\ToString;
|
||||
use Rinsvent\Transformer\Transformer\Trim;
|
||||
|
||||
#[HelloSchema]
|
||||
class HelloRequest
|
||||
{
|
||||
#[Trim]
|
||||
public string $surname;
|
||||
#[DataPath('fake_age')]
|
||||
public int $age;
|
||||
public array $emails;
|
||||
public array $authors;
|
||||
@ -19,6 +19,151 @@ class HelloRequest
|
||||
public array $authors3;
|
||||
public BuyRequest $buy;
|
||||
public BarInterface $bar;
|
||||
#[PropertyPath(path: 'uuid.id')]
|
||||
#[ToString()]
|
||||
public UUID $uuid;
|
||||
public Collection $collection;
|
||||
#[DateTimeFormat]
|
||||
public \DateTimeImmutable $createdAt;
|
||||
|
||||
#[Trim]
|
||||
private string $psurname;
|
||||
private int $page;
|
||||
private array $pemails;
|
||||
private array $pauthors;
|
||||
private array $pauthors2;
|
||||
private array $pauthors3;
|
||||
private BuyRequest $pbuy;
|
||||
private BarInterface $pbar;
|
||||
#[ToString()]
|
||||
private UUID $puuid;
|
||||
private Collection $pcollection;
|
||||
#[DateTimeFormat]
|
||||
private \DateTimeImmutable $pcreatedAt;
|
||||
|
||||
public function getPsurname(): string
|
||||
{
|
||||
return $this->psurname;
|
||||
}
|
||||
|
||||
public function setPsurname(string $psurname): self
|
||||
{
|
||||
$this->psurname = $psurname;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPage(): int
|
||||
{
|
||||
return $this->page;
|
||||
}
|
||||
|
||||
public function setPage(int $page): self
|
||||
{
|
||||
$this->page = $page;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPemails(): array
|
||||
{
|
||||
return $this->pemails;
|
||||
}
|
||||
|
||||
public function setPemails(array $pemails): self
|
||||
{
|
||||
$this->pemails = $pemails;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPauthors(): array
|
||||
{
|
||||
return $this->pauthors;
|
||||
}
|
||||
|
||||
public function setPauthors(array $pauthors): self
|
||||
{
|
||||
$this->pauthors = $pauthors;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPauthors2(): array
|
||||
{
|
||||
return $this->pauthors2;
|
||||
}
|
||||
|
||||
public function setPauthors2(array $pauthors2): self
|
||||
{
|
||||
$this->pauthors2 = $pauthors2;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPauthors3(): array
|
||||
{
|
||||
return $this->pauthors3;
|
||||
}
|
||||
|
||||
public function setPauthors3(array $pauthors3): self
|
||||
{
|
||||
$this->pauthors3 = $pauthors3;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPbuy(): BuyRequest
|
||||
{
|
||||
return $this->pbuy;
|
||||
}
|
||||
|
||||
public function setPbuy(BuyRequest $pbuy): self
|
||||
{
|
||||
$this->pbuy = $pbuy;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPuuid(): UUID
|
||||
{
|
||||
return $this->puuid;
|
||||
}
|
||||
|
||||
public function setPuuid(UUID $puuid): self
|
||||
{
|
||||
$this->puuid = $puuid;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPbar(): BarInterface
|
||||
{
|
||||
return $this->pbar;
|
||||
}
|
||||
|
||||
public function setPbar(BarInterface $pbar): self
|
||||
{
|
||||
$this->pbar = $pbar;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPcollection(): Collection
|
||||
{
|
||||
return $this->pcollection;
|
||||
}
|
||||
|
||||
public function setPcollection(Collection $pcollection): self
|
||||
{
|
||||
$this->pcollection = $pcollection;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPcreatedAt(): \DateTimeImmutable
|
||||
{
|
||||
return $this->pcreatedAt;
|
||||
}
|
||||
|
||||
public function setPcreatedAt(\DateTimeImmutable $pcreatedAt): self
|
||||
{
|
||||
$this->pcreatedAt = $pcreatedAt;
|
||||
return $this;
|
||||
}
|
||||
|
||||
#[Trim]
|
||||
public function getPdevdo(): string
|
||||
{
|
||||
return ' getPdevdo';
|
||||
}
|
||||
}
|
||||
|
@ -7,9 +7,9 @@ use Rinsvent\DTO2Data\Attribute\Schema;
|
||||
#[\Attribute(\Attribute::TARGET_ALL|\Attribute::IS_REPEATABLE)]
|
||||
class HelloSchema extends Schema
|
||||
{
|
||||
public ?array $baseMap = [
|
||||
protected array $baseMap = [
|
||||
'surname',
|
||||
'age',
|
||||
'fake_age' => 'age',
|
||||
'emails',
|
||||
'authors' => [
|
||||
'name',
|
||||
@ -26,6 +26,36 @@ class HelloSchema extends Schema
|
||||
'bar' => [
|
||||
'barField'
|
||||
],
|
||||
'uuid'
|
||||
'uuid',
|
||||
'collection' => [
|
||||
'value'
|
||||
],
|
||||
'createdAt',
|
||||
|
||||
'psurname',
|
||||
'pfake_age' => 'page',
|
||||
'pemails',
|
||||
'pauthors' => [
|
||||
'name',
|
||||
],
|
||||
'pauthors2' => [
|
||||
'name',
|
||||
],
|
||||
'pauthors3',
|
||||
'pbuy' => [
|
||||
'phrase',
|
||||
'length',
|
||||
'isFirst',
|
||||
],
|
||||
'pbar' => [
|
||||
'barField'
|
||||
],
|
||||
'puuid',
|
||||
'pcollection' => [
|
||||
'value'
|
||||
],
|
||||
'pcreatedAt',
|
||||
|
||||
'fake_Pdevdo' => 'pdevdo'
|
||||
];
|
||||
}
|
||||
|
@ -1,18 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest;
|
||||
|
||||
use Rinsvent\DTO2Data\Attribute\DataPath;
|
||||
use Rinsvent\DTO2Data\Attribute\HandleTags;
|
||||
|
||||
#[HandleTags(method: 'getTags')]
|
||||
class HelloTagsRequest extends HelloRequest
|
||||
{
|
||||
#[DataPath('fake_age2', tags: ['surname-group'])]
|
||||
public int $age;
|
||||
|
||||
public function getTags(array $tags)
|
||||
{
|
||||
return 'Surname1234' === trim(($this->surname ?? '')) ? ['surname-group'] : $tags;
|
||||
}
|
||||
}
|
@ -2,7 +2,7 @@
|
||||
|
||||
namespace Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest\Transformer;
|
||||
|
||||
use Rinsvent\DTO2Data\Transformer\Meta;
|
||||
use Rinsvent\Transformer\Transformer\Meta;
|
||||
|
||||
#[\Attribute]
|
||||
class ClassData extends Meta
|
||||
|
@ -2,8 +2,8 @@
|
||||
|
||||
namespace Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest\Transformer;
|
||||
|
||||
use Rinsvent\DTO2Data\Transformer\Meta;
|
||||
use Rinsvent\DTO2Data\Transformer\TransformerInterface;
|
||||
use Rinsvent\Transformer\Transformer\Meta;
|
||||
use Rinsvent\Transformer\Transformer\TransformerInterface;
|
||||
|
||||
class ClassDataTransformer implements TransformerInterface
|
||||
{
|
||||
@ -11,14 +11,15 @@ class ClassDataTransformer implements TransformerInterface
|
||||
* @param array|null $data
|
||||
* @param ClassData $meta
|
||||
*/
|
||||
public function transform(&$data, Meta $meta): void
|
||||
public function transform(mixed $data, Meta $meta): mixed
|
||||
{
|
||||
if ($data === null) {
|
||||
return;
|
||||
return $data;
|
||||
}
|
||||
|
||||
if (isset($data['surname'])) {
|
||||
$data['surname'] = '123454321';
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
|
@ -2,7 +2,7 @@
|
||||
|
||||
namespace Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest\Transformer;
|
||||
|
||||
use Rinsvent\DTO2Data\Transformer\Meta;
|
||||
use Rinsvent\Transformer\Transformer\Meta;
|
||||
|
||||
#[\Attribute]
|
||||
class ClassObject extends Meta
|
||||
|
@ -3,8 +3,8 @@
|
||||
namespace Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest\Transformer;
|
||||
|
||||
use Rinsvent\DTO2Data\Tests\unit\Converter\fixtures\FillTest\HelloClassTransformersRequest2;
|
||||
use Rinsvent\DTO2Data\Transformer\Meta;
|
||||
use Rinsvent\DTO2Data\Transformer\TransformerInterface;
|
||||
use Rinsvent\Transformer\Transformer\Meta;
|
||||
use Rinsvent\Transformer\Transformer\TransformerInterface;
|
||||
|
||||
class ClassObjectTransformer implements TransformerInterface
|
||||
{
|
||||
@ -12,13 +12,14 @@ class ClassObjectTransformer implements TransformerInterface
|
||||
* @param array|null $data
|
||||
* @param ClassData $meta
|
||||
*/
|
||||
public function transform(&$data, Meta $meta): void
|
||||
public function transform(mixed $data, Meta $meta): mixed
|
||||
{
|
||||
if ($data === null) {
|
||||
return;
|
||||
return $data;
|
||||
}
|
||||
$object = new HelloClassTransformersRequest2();
|
||||
$object->surname = '98789';
|
||||
$data = $object;
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
|
@ -11,4 +11,9 @@ class UUID
|
||||
{
|
||||
$this->id = $id;
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user