File: Expect.castTo.phpt

package info (click to toggle)
php-nette-schema 1.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 324 kB
  • sloc: php: 925; makefile: 8
file content (69 lines) | stat: -rw-r--r-- 1,199 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php

declare(strict_types=1);

use Nette\Schema\Expect;
use Nette\Schema\Processor;
use Tester\Assert;


require __DIR__ . '/../bootstrap.php';


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('simple object', function () {
	class Foo1
	{
		public $a;
		public $b;
	}

	$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('object with constructor', function () {
	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]),
	);
});


test('DateTime', function () {
	$schema = Expect::string()->castTo(DateTime::class);
	Assert::equal(
		new DateTime('2021-01-01'),
		(new Processor)->process($schema, '2021-01-01'),
	);
});