Expect.castTo.phpt 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. declare(strict_types=1);
  3. use Nette\Schema\Expect;
  4. use Nette\Schema\Processor;
  5. use Tester\Assert;
  6. require __DIR__ . '/../bootstrap.php';
  7. test('built-in', function () {
  8. $schema = Expect::int()->castTo('string');
  9. Assert::same('10', (new Processor)->process($schema, 10));
  10. $schema = Expect::string()->castTo('array');
  11. Assert::same(['foo'], (new Processor)->process($schema, 'foo'));
  12. });
  13. test('simple object', function () {
  14. class Foo1
  15. {
  16. public $a;
  17. public $b;
  18. }
  19. $foo = new Foo1;
  20. $foo->a = 1;
  21. $foo->b = 2;
  22. $schema = Expect::array()->castTo(Foo1::class);
  23. Assert::equal(
  24. $foo,
  25. (new Processor)->process($schema, ['a' => 1, 'b' => 2])
  26. );
  27. });
  28. test('object with constructor', function () {
  29. if (PHP_VERSION_ID < 80000) {
  30. return;
  31. }
  32. class Foo2
  33. {
  34. private $a;
  35. private $b;
  36. public function __construct(int $a, int $b)
  37. {
  38. $this->b = $b;
  39. $this->a = $a;
  40. }
  41. }
  42. $schema = Expect::array()->castTo(Foo2::class);
  43. Assert::equal(
  44. new Foo2(1, 2),
  45. (new Processor)->process($schema, ['b' => 2, 'a' => 1])
  46. );
  47. });
  48. test('DateTime', function () {
  49. $schema = Expect::string()->castTo(DateTime::class);
  50. Assert::equal(
  51. new DateTime('2021-01-01'),
  52. (new Processor)->process($schema, '2021-01-01')
  53. );
  54. });