Skip to content

Commit

Permalink
single schema mapping
Browse files Browse the repository at this point in the history
  • Loading branch information
Smoren committed Aug 5, 2022
1 parent 715d27b commit cd54a17
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
12 changes: 10 additions & 2 deletions src/Schemator.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,18 @@ public function __construct(string $pathDelimiter = '.')
* Converts input data with using schema
* @param array $source input data to convert
* @param array $schema schema for converting
* @return array converted data
* @return array|mixed converted data
* @throws SchematorException
*/
public function exec(array $source, array $schema): array
public function exec(array $source, array $schema)
{
$result = [];

foreach($schema as $key => $schemaItem) {
$this->saveByPath($result, $key, $this->getValue($source, $schemaItem));
if($key === '') {
break;
}
}

return $result;
Expand Down Expand Up @@ -186,6 +189,11 @@ protected function runFilter(array $filterConfig, $source, array $rootSource)
*/
protected function saveByPath(array &$source, string $path, $value): self
{
if($path === '') {
$source = $value;
return $this;
}

$arPath = explode($this->pathDelimiter, $path);
$temp = &$source;
foreach($arPath as $key) {
Expand Down
16 changes: 14 additions & 2 deletions tests/unit/MassSchematorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public function testNested()
$result[] = $item;
}

$exprectedResult = [
$expectedResult = [
[
'my_city_id' => 100,
'my_country' => [
Expand All @@ -98,7 +98,19 @@ public function testNested()
],
];

$this->assertEquals($exprectedResult, $result);
$this->assertEquals($expectedResult, $result);
}

public function testExtra()
{
$massSchemator = new MassSchemator(new Schemator());
$cities = $this->getCities();

$result = $massSchemator->exec($cities, [
'' => 'name',
]);

$this->assertEquals(['Novgorod', 'Moscow'], $result);
}

/**
Expand Down

0 comments on commit cd54a17

Please sign in to comment.