Skip to content

Commit

Permalink
fix: allow missing value for shaped array nullable node in flexible mode
Browse files Browse the repository at this point in the history
  • Loading branch information
romm committed Nov 7, 2022
1 parent 25ce218 commit 08fb0e1
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 48 deletions.
10 changes: 3 additions & 7 deletions src/Mapper/Tree/Builder/ShapedArrayNodeBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace CuyZ\Valinor\Mapper\Tree\Builder;

use CuyZ\Valinor\Mapper\Tree\Exception\ShapedArrayElementMissing;
use CuyZ\Valinor\Mapper\Tree\Exception\SourceMustBeIterable;
use CuyZ\Valinor\Mapper\Tree\Exception\UnexpectedShapedArrayKeys;
use CuyZ\Valinor\Mapper\Tree\Shell;
Expand Down Expand Up @@ -59,15 +58,12 @@ private function children(ShapedArrayType $type, Shell $shell, RootNodeBuilder $

$child = $shell->child((string)$key, $element->type());

if (! array_key_exists($key, $value)) {
if (! $element->isOptional()) {
$children[$key] = TreeNode::error($child, new ShapedArrayElementMissing($element));
}

if (array_key_exists($key, $value)) {
$child = $child->withValue($value[$key]);
} elseif ($element->isOptional()) {
continue;
}

$child = $child->withValue($value[$key]);
$children[$key] = $rootBuilder->build($child);

unset($value[$key]);
Expand Down
40 changes: 0 additions & 40 deletions src/Mapper/Tree/Exception/ShapedArrayElementMissing.php

This file was deleted.

15 changes: 15 additions & 0 deletions tests/Integration/Mapping/Other/FlexibleMappingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,21 @@ public function test_missing_value_for_nullable_property_fills_it_with_null(): v
self::assertSame(null, $result->bar);
}

public function test_missing_value_for_nullable_shaped_array_element_fills_it_with_null(): void
{
try {
$result = (new MapperBuilder())->flexible()->mapper()->map(
'array{foo: string, bar: ?string}',
['foo' => 'foo']
);
} catch (MappingError $error) {
$this->mappingFail($error);
}

self::assertSame('foo', $result['foo']);
self::assertSame(null, $result['bar']);
}

public function test_value_that_cannot_be_cast_throws_exception(): void
{
try {
Expand Down
2 changes: 1 addition & 1 deletion tests/Integration/Mapping/Other/ShapedArrayMappingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public function test_missing_element_throws_exception(): void
} catch (MappingError $exception) {
$error = $exception->node()->children()['bar']->messages()[0];

self::assertSame('1631613641', $error->code());
self::assertSame('1655449641', $error->code());
self::assertSame('Cannot be empty and must be filled with a value matching type `int`.', (string)$error);
}
}
Expand Down

0 comments on commit 08fb0e1

Please sign in to comment.