Проинтегрировал обработку массивов ДТО

This commit is contained in:
Rinsvent 2021-08-08 14:01:51 +07:00
parent 351707da65
commit 3f403ba077
5 changed files with 56 additions and 0 deletions

11
src/Attribute/DTOMeta.php Normal file
View File

@ -0,0 +1,11 @@
<?php
namespace Rinsvent\Data2DTO\Attribute;
#[\Attribute]
class DTOMeta
{
public function __construct(
public string $class
) {}
}

View File

@ -3,6 +3,7 @@
namespace Rinsvent\Data2DTO;
use Rinsvent\AttributeExtractor\PropertyExtractor;
use Rinsvent\Data2DTO\Attribute\DTOMeta;
use Rinsvent\Data2DTO\Attribute\PropertyPath;
use Rinsvent\Data2DTO\Resolver\TransformerResolverStorage;
use Rinsvent\Data2DTO\Transformer\Meta;
@ -37,6 +38,27 @@ class Data2DtoConverter
$property->setValue($object, $value);
continue;
}
$attributedPropertyClass = null;
$propertyName = $property->getName();
$propertyExtractor = new PropertyExtractor($property->class, $propertyName);
/** @var DTOMeta $dtoMeta */
if ($dtoMeta = $propertyExtractor->fetch(DTOMeta::class)) {
$attributedPropertyClass = $dtoMeta->class;
}
// Если массив и есть атрибут с указанием класса, то также преобразуем структуру
if ($propertyType === 'array' && $attributedPropertyClass) {
// Если тип у ДТО - массив, а в значении не массив - пропустим
if (!is_array($value)) {
continue;
}
$tempValue = [];
foreach ($value as $itemValue) {
$tempValue[] = $this->convert($itemValue, $attributedPropertyClass);
}
$value = $tempValue;
}
// Если это class, то рекурсивно заполняем дальше
if (class_exists($propertyType)) {
$value = $this->convert($value, $propertyType);

View File

@ -33,6 +33,14 @@ class FillTest extends \Codeception\Test\Unit
'af234f',
'asdf33333'
],
'authors' => [
[
'name' => 'Tolkien',
],
[
'name' => 'Sapkovsky'
]
],
'buy' => [
'phrase' => 'Buy buy!!!',
'length' => 10,
@ -53,5 +61,9 @@ class FillTest extends \Codeception\Test\Unit
$this->assertEquals('Buy buy!!!', $dto->buy->phrase);
$this->assertEquals(10, $dto->buy->length);
$this->assertEquals(true, $dto->buy->isFirst);
$this->assertCount(2, $dto->authors);
$this->assertEquals('Tolkien', $dto->authors[0]->name);
$this->assertEquals('Sapkovsky', $dto->authors[1]->name);
}
}

View File

@ -0,0 +1,8 @@
<?php
namespace Rinsvent\Data2DTO\Tests\unit\Converter\fixtures\FillTest;
class Author
{
public string $name;
}

View File

@ -2,6 +2,7 @@
namespace Rinsvent\Data2DTO\Tests\unit\Converter\fixtures\FillTest;
use Rinsvent\Data2DTO\Attribute\DTOMeta;
use Rinsvent\Data2DTO\Attribute\PropertyPath;
use Rinsvent\Data2DTO\Transformer\Trim;
@ -12,5 +13,7 @@ class HelloRequest
#[PropertyPath('fake_age')]
public int $age;
public array $emails;
#[DTOMeta(class: Author::class)]
public array $authors;
public BuyRequest $buy;
}