Expect.scalars.phpt 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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('', function () {
  8. $schema = Expect::scalar();
  9. Assert::same('hello', (new Processor)->process($schema, 'hello'));
  10. Assert::same(123, (new Processor)->process($schema, 123));
  11. Assert::same(false, (new Processor)->process($schema, false));
  12. checkValidationErrors(function () use ($schema) {
  13. (new Processor)->process($schema, null);
  14. }, ['The item expects to be scalar, null given.']);
  15. checkValidationErrors(function () use ($schema) {
  16. (new Processor)->process($schema, []);
  17. }, ['The item expects to be scalar, array given.']);
  18. });
  19. test('', function () {
  20. $schema = Expect::string();
  21. Assert::same('hello', (new Processor)->process($schema, 'hello'));
  22. checkValidationErrors(function () use ($schema) {
  23. (new Processor)->process($schema, 123);
  24. }, ['The item expects to be string, 123 given.']);
  25. checkValidationErrors(function () use ($schema) {
  26. (new Processor)->process($schema, null);
  27. }, ['The item expects to be string, null given.']);
  28. checkValidationErrors(function () use ($schema) {
  29. (new Processor)->process($schema, false);
  30. }, ['The item expects to be string, false given.']);
  31. checkValidationErrors(function () use ($schema) {
  32. (new Processor)->process($schema, []);
  33. }, ['The item expects to be string, array given.']);
  34. });
  35. test('', function () {
  36. $schema = Expect::type('string|bool');
  37. Assert::same('one', (new Processor)->process($schema, 'one'));
  38. Assert::same(true, (new Processor)->process($schema, true));
  39. checkValidationErrors(function () use ($schema) {
  40. (new Processor)->process($schema, 123);
  41. }, ['The item expects to be string or bool, 123 given.']);
  42. checkValidationErrors(function () use ($schema) {
  43. (new Processor)->process($schema, null);
  44. }, ['The item expects to be string or bool, null given.']);
  45. checkValidationErrors(function () use ($schema) {
  46. (new Processor)->process($schema, []);
  47. }, ['The item expects to be string or bool, array given.']);
  48. });
  49. test('', function () {
  50. $schema = Expect::type('string')->nullable();
  51. Assert::same('one', (new Processor)->process($schema, 'one'));
  52. checkValidationErrors(function () use ($schema) {
  53. (new Processor)->process($schema, 123);
  54. }, ['The item expects to be null or string, 123 given.']);
  55. Assert::same(null, (new Processor)->process($schema, null));
  56. });