Expect.before.phpt 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. declare(strict_types=1);
  3. use Nette\Schema\Context;
  4. use Nette\Schema\Expect;
  5. use Tester\Assert;
  6. require __DIR__ . '/../bootstrap.php';
  7. test('', function () {
  8. $schema = Expect::array()
  9. ->before(function ($val) { return explode(',', $val); });
  10. Assert::same(
  11. ['1', '2', '3'],
  12. $schema->normalize('1,2,3', new Context)
  13. );
  14. });
  15. test('structure property', function () {
  16. $schema = Expect::structure([
  17. 'key' => Expect::string()->before('strrev'),
  18. ]);
  19. Assert::same(
  20. ['key' => '3,2,1'],
  21. $schema->normalize(['key' => '1,2,3'], new Context)
  22. );
  23. });
  24. test('order in structure', function () {
  25. $schema = Expect::structure([
  26. 'a' => Expect::string()->before(function ($val) use (&$order) {
  27. $order[] = 'a';
  28. return $val;
  29. }),
  30. 'b' => Expect::string()->before(function ($val) use (&$order) {
  31. $order[] = 'b';
  32. return $val;
  33. }),
  34. ])
  35. ->otherItems(Expect::string()->before(function ($val) use (&$order) {
  36. $order[] = 'other';
  37. return $val;
  38. }))
  39. ->before(function ($val) use (&$order) {
  40. $order[] = 'struct';
  41. return $val;
  42. });
  43. $order = [];
  44. Assert::null($schema->normalize(null, new Context));
  45. Assert::same(['struct'], $order);
  46. $order = [];
  47. Assert::same(['a' => 1], $schema->normalize(['a' => 1], new Context));
  48. Assert::same(['struct', 'a'], $order);
  49. $order = [];
  50. Assert::same(['a' => '1'], $schema->normalize(['a' => '1'], new Context));
  51. Assert::same(['struct', 'a'], $order);
  52. $order = [];
  53. Assert::same(['a' => 1, 'c' => 1], $schema->normalize(['a' => 1, 'c' => 1], new Context));
  54. Assert::same(['struct', 'a', 'other'], $order);
  55. $order = [];
  56. Assert::same(['c' => 1], $schema->normalize(['c' => 1], new Context));
  57. Assert::same(['struct', 'other'], $order);
  58. });
  59. test('order in array', function () {
  60. $schema = Expect::array()
  61. ->items(Expect::string()->before(function ($val) use (&$order) {
  62. $order[] = 'item';
  63. return $val;
  64. }))
  65. ->before(function ($val) use (&$order) {
  66. $order[] = 'array';
  67. return $val;
  68. });
  69. $order = [];
  70. Assert::null($schema->normalize(null, new Context));
  71. Assert::same(['array'], $order);
  72. $order = [];
  73. Assert::same(['a' => 1], $schema->normalize(['a' => 1], new Context));
  74. Assert::same(['array', 'item'], $order);
  75. });