Expect.from.phpt 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. declare(strict_types=1);
  3. use Nette\Schema\Elements\Structure;
  4. use Nette\Schema\Expect;
  5. use Nette\Schema\Processor;
  6. use Tester\Assert;
  7. require __DIR__ . '/../bootstrap.php';
  8. if (!class_exists(Nette\Utils\Type::class)) {
  9. Tester\Environment::skip('Expect::from() requires nette/utils 3.x');
  10. }
  11. Assert::with(Structure::class, function () {
  12. $schema = Expect::from(new stdClass);
  13. Assert::type(Structure::class, $schema);
  14. Assert::same([], $schema->items);
  15. Assert::type(stdClass::class, (new Processor)->process($schema, []));
  16. });
  17. Assert::with(Structure::class, function () {
  18. $schema = Expect::from($obj = new class {
  19. /** @var string */
  20. public $dsn = 'mysql';
  21. /** @var string|null */
  22. public $user;
  23. /** @var ?string */
  24. public $password;
  25. /** @var string[] */
  26. public $options = [1];
  27. /** @var bool */
  28. public $debugger = true;
  29. public $mixed;
  30. /** @var array|null */
  31. public $arr;
  32. /** @var string */
  33. public $required;
  34. });
  35. Assert::type(Structure::class, $schema);
  36. Assert::equal([
  37. 'dsn' => Expect::string('mysql'),
  38. 'user' => Expect::type('string|null'),
  39. 'password' => Expect::type('?string'),
  40. 'options' => Expect::type('string[]')->default([1]),
  41. 'debugger' => Expect::bool(true),
  42. 'mixed' => Expect::mixed(),
  43. 'arr' => Expect::type('array|null')->default(null),
  44. 'required' => Expect::type('string')->required(),
  45. ], $schema->items);
  46. Assert::type($obj, (new Processor)->process($schema, ['required' => '']));
  47. });
  48. Assert::exception(function () {
  49. Expect::from(new class {
  50. /** @var Unknown */
  51. public $unknown;
  52. });
  53. }, Nette\NotImplementedException::class, 'Anonymous classes are not supported.');
  54. Assert::with(Structure::class, function () { // overwritten item
  55. $schema = Expect::from(new class {
  56. /** @var string */
  57. public $dsn = 'mysql';
  58. /** @var string|null */
  59. public $user;
  60. }, ['dsn' => Expect::int(123)]);
  61. Assert::equal([
  62. 'dsn' => Expect::int(123),
  63. 'user' => Expect::type('string|null'),
  64. ], $schema->items);
  65. });
  66. Assert::with(Structure::class, function () { // nested object
  67. $obj = new class {
  68. /** @var object */
  69. public $inner;
  70. };
  71. $obj->inner = new class {
  72. /** @var string */
  73. public $name;
  74. };
  75. $schema = Expect::from($obj);
  76. Assert::equal([
  77. 'inner' => Expect::structure([
  78. 'name' => Expect::string()->required(),
  79. ])->castTo(get_class($obj->inner)),
  80. ], $schema->items);
  81. });