Skip to content

Commit

Permalink
added callback decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
proggeler committed May 31, 2024
1 parent 20da03a commit 4cbf73e
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 1 deletion.
21 changes: 21 additions & 0 deletions src/Decorators/CallbackDecorator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace DMT\Import\Reader\Decorators;

use Closure;

class CallbackDecorator implements DecoratorInterface
{

private Closure $callback;

public function __construct(Closure $callback)
{
$this->callback = $callback;
}

public function decorate(object $currentRow): object
{
return call_user_func($this->callback, $currentRow) ?? $currentRow;
}
}
2 changes: 1 addition & 1 deletion src/Decorators/Xml/XmlToObjectDecorator.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function __construct(string $fqcn, array $mapping)
*
* This tries to initiate and populate a DataTransferObject.
*
* @param SimpleXMLElement|object $currentRow The current csv row.
* @param SimpleXMLElement|object $currentRow The current xml row.
*
* @return object Instance of an object according to type stored in fqcn.
* @throws DecoratorException When the initialization of the object failed.
Expand Down
56 changes: 56 additions & 0 deletions tests/Decorators/CallbackDecoratorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace DMT\Test\Import\Reader\Decorators;

use ArrayObject;
use Closure;
use DMT\Import\Reader\Decorators\CallbackDecorator;
use PHPUnit\Framework\TestCase;
use SimpleXMLElement;

class CallbackDecoratorTest extends TestCase
{
/**
* @dataProvider provideRow
*
* @param Closure $callback
* @param object $currentRow
* @param object $expected
*/
public function testDecorate(Closure $callback, object $currentRow, object $expected): void
{
$decorator = new CallbackDecorator($callback);

$this->assertEquals($expected, $decorator->decorate($currentRow));
}

public function provideRow(): iterable
{
return [
'xml' => [
function (SimpleXMLElement $currentRow) {
$currentRow->addChild('type', (string) $currentRow->car->attributes()['type']);
foreach ($currentRow->xpath('car/@*') as $attribute) {
unset($attribute[0]);
}
},
simplexml_load_string('<root><car type="focus">ford</car></root>'),
simplexml_load_string('<root><car>ford</car><type>focus</type></root>')
],
'json' => [
function (object $currentRow) {
$currentRow->lorem = 'ipsum';
},
json_decode('{"foo": "bar"}'),
(object) ['foo' => 'bar', 'lorem' => 'ipsum']
],
'csv (pass through)' => [
function (object $currentRow) {
$currentRow['col2'] = 'value2';
},
new ArrayObject(['col1' => 'value1']),
new ArrayObject(['col1' => 'value1', 'col2' => 'value2']),
],
];
}
}

0 comments on commit 4cbf73e

Please sign in to comment.