Skip to content

Commit

Permalink
Added an ignore attribute to skip certain properties when necassary
Browse files Browse the repository at this point in the history
  • Loading branch information
WeTurkstra committed May 31, 2024
1 parent 855b987 commit 1461859
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.3/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
beStrictAboutOutputDuringTests="true"
>
<testsuites>
<testsuite name="Test Suite">
Expand Down
9 changes: 9 additions & 0 deletions src/Attribute/Ignore.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace Tibisoft\AutoTransformer\Attribute;

#[\Attribute(\Attribute::TARGET_PROPERTY)]
class Ignore
{

}
5 changes: 5 additions & 0 deletions src/AutoTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Tibisoft\AutoTransformer\Attribute\AttributeHandlerInterface;
use Tibisoft\AutoTransformer\Attribute\BaseAttribute;
use Tibisoft\AutoTransformer\Attribute\Ignore;
use Tibisoft\AutoTransformer\Exception\TransformException;

class AutoTransformer implements AutoTransformerInterface
Expand All @@ -23,6 +24,10 @@ public function transform(object $from, string|object $to): object

foreach ($attributes as $attribute) {
$attribute = $attribute->newInstance();
if($attribute instanceof Ignore) {
continue 2;
}

if (!($attribute instanceof BaseAttribute)) {
continue;
}
Expand Down
42 changes: 42 additions & 0 deletions tests/Transformer/Attribute/IgnoreTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

test('Test ignore Attribute', function () {
$object = new IgnoreClass(10, 'Willem Turkstra', ['test' => ['something' => 'missing']]);

$transformer = new \Tibisoft\AutoTransformer\AutoTransformer();

/** @var IgnoreClassDTO $dto */
$dto = $transformer->transform($object, IgnoreClassDTO::class);

expect($dto->age)->toBe($object->age);
expect($dto->name)->toBe($object->name);

$refProp = new ReflectionProperty($dto, 'complexArray');
expect($refProp->isInitialized($dto))->toBe(false);

});

class IgnoreClass
{
public function __construct(
public int $age,
public string $name,
public array $complexArray,
)
{

}
}

class IgnoreClassDTO
{
public function __construct(
public int $age,
public string $name,
#[\Tibisoft\AutoTransformer\Attribute\Ignore]
public array $complexArray,
)
{

}
}

0 comments on commit 1461859

Please sign in to comment.