Skip to content

Commit

Permalink
castTo() allows you to create objects [Closes #44][Closes #47]
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Oct 2, 2023
1 parent ab69dae commit 5a22fb8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
6 changes: 5 additions & 1 deletion src/Schema/Elements/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,12 @@ private function doFinalize(mixed $value, Context $context)
if ($this->castTo) {
if (Nette\Utils\Validators::isBuiltinType($this->castTo)) {
settype($value, $this->castTo);
} else {
} elseif (strcasecmp($this->castTo, \stdClass::class) === 0) {
$value = Nette\Utils\Arrays::toObject($value, new $this->castTo);
} else {
$value = is_array($value)
? new ($this->castTo)(...$value)
: new ($this->castTo)($value);
}
}

Expand Down
28 changes: 20 additions & 8 deletions tests/Schema/Expect.castTo.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,34 @@ use Tester\Assert;
require __DIR__ . '/../bootstrap.php';


test('', function () {
test('built-in', function () {
$schema = Expect::int()->castTo('string');

Assert::same('10', (new Processor)->process($schema, 10));
});


test('', function () {
$schema = Expect::string()->castTo('array');

Assert::same(['foo'], (new Processor)->process($schema, 'foo'));
});


test('', function () {
test('stdClass', function () {
$schema = Expect::array()->castTo('stdClass');
Assert::equal(
(object) ['a' => 1, 'b' => 2],
(new Processor)->process($schema, ['a' => 1, 'b' => 2]),
);
});


test('DateTime', function () {
$schema = Expect::array()->castTo('DateTime');
Assert::equal(
new DateTime('2021-01-01'),
(new Processor)->process($schema, ['datetime' => '2021-01-01']),
);

Assert::equal((object) ['a' => 1, 'b' => 2], (new Processor)->process($schema, ['a' => 1, 'b' => 2]));
$schema = Expect::string()->castTo('DateTime');
Assert::equal(
new DateTime('2021-01-01'),
(new Processor)->process($schema, '2021-01-01'),
);
});

0 comments on commit 5a22fb8

Please sign in to comment.