Expect.transform.phpt 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. declare(strict_types=1);
  3. use Nette\Schema\Context;
  4. use Nette\Schema\Expect;
  5. use Nette\Schema\Processor;
  6. use Tester\Assert;
  7. require __DIR__ . '/../bootstrap.php';
  8. test('simple tranformation', function () {
  9. $schema = Expect::string()->transform(function ($s) { return strrev($s); });
  10. Assert::same('olleh', (new Processor)->process($schema, 'hello'));
  11. });
  12. test('validation via transform', function () {
  13. $schema = Expect::int()
  14. ->transform(function ($val, Context $context) {
  15. if ($val > 3) {
  16. $context->addError('Bigger than 3', 'my');
  17. }
  18. return $val;
  19. })
  20. ->transform(function ($s, Context $context) {
  21. if ($s > 5) {
  22. $context->addError('Bigger than 5', 'my');
  23. }
  24. return $s;
  25. });
  26. checkValidationErrors(function () use ($schema) {
  27. (new Processor)->process($schema, 10);
  28. }, ['Bigger than 3']);
  29. Assert::same(2, (new Processor)->process($schema, 2));
  30. });
  31. test('multiple tranformation/assertions', function () {
  32. $schema = Expect::string()
  33. ->assert('ctype_lower')
  34. ->transform(function ($s) { return strtoupper($s); })
  35. ->assert('ctype_upper')
  36. ->transform(function ($s) { return strrev($s); });
  37. checkValidationErrors(function () use ($schema) {
  38. (new Processor)->process($schema, 'ABC');
  39. }, ["Failed assertion ctype_lower() for item with value 'ABC'."]);
  40. Assert::same('CBA', (new Processor)->process($schema, 'abc'));
  41. });