Skip to content

Commit

Permalink
castTo() allows you to create objects [Closes #44][Closes #47][Closes #…
Browse files Browse the repository at this point in the history
…58][Closes #46]
  • Loading branch information
dg committed Oct 4, 2023
1 parent 19c17e4 commit 41ecbc6
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 8 deletions.
9 changes: 9 additions & 0 deletions src/Schema/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,15 @@ public static function getCastStrategy(string $type): \Closure
settype($value, $type);
return $value;
};
} elseif (method_exists($type, '__construct')) {
return static function ($value) use ($type) {
if (PHP_VERSION_ID < 80000 && is_array($value)) {
throw new Nette\NotSupportedException("Creating $type objects is supported since PHP 8.0");
}
return is_array($value)
? new $type(...$value)
: new $type($value);
};
} else {
return static function ($value) use ($type) {
$object = new $type;
Expand Down
58 changes: 50 additions & 8 deletions tests/Schema/Expect.castTo.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,64 @@ 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));

$schema = Expect::string()->castTo('array');
Assert::same(['foo'], (new Processor)->process($schema, 'foo'));
});


test('', function () {
$schema = Expect::string()->castTo('array');
test('simple object', function () {
class Foo1
{
public $a;
public $b;
}

Assert::same(['foo'], (new Processor)->process($schema, 'foo'));
$foo = new Foo1;
$foo->a = 1;
$foo->b = 2;

$schema = Expect::array()->castTo(Foo1::class);
Assert::equal(
$foo,
(new Processor)->process($schema, ['a' => 1, 'b' => 2])
);
});


test('', function () {
$schema = Expect::array()->castTo('stdClass');
test('object with constructor', function () {
if (PHP_VERSION_ID < 80000) {
return;
}

class Foo2
{
private $a;
private $b;


public function __construct(int $a, int $b)
{
$this->b = $b;
$this->a = $a;
}
}

$schema = Expect::array()->castTo(Foo2::class);
Assert::equal(
new Foo2(1, 2),
(new Processor)->process($schema, ['b' => 2, 'a' => 1])
);
});


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

0 comments on commit 41ecbc6

Please sign in to comment.