PageRenderTime 47ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/library/Respect/Validation/Rules/Each.php

http://github.com/Respect/Validation
PHP | 103 lines | 82 code | 21 blank | 0 comment | 18 complexity | 93f2e4bc22845b30a199a8c307a812ac MD5 | raw file
Possible License(s): MIT, BSD-3-Clause
  1. <?php
  2. namespace Respect\Validation\Rules;
  3. use Traversable;
  4. use Respect\Validation\Validatable;
  5. use Respect\Validation\Exceptions\ValidationException;
  6. class Each extends AbstractRule
  7. {
  8. public $itemValidator;
  9. public $keyValidator;
  10. public function __construct(Validatable $itemValidator = null,
  11. Validatable $keyValidator=null)
  12. {
  13. $this->itemValidator = $itemValidator;
  14. $this->keyValidator = $keyValidator;
  15. }
  16. public function assert($input)
  17. {
  18. $exceptions = array();
  19. if (!is_array($input) || $input instanceof Traversable) {
  20. throw $this->reportError($input);
  21. }
  22. if (empty($input)) {
  23. return true;
  24. }
  25. foreach ($input as $key => $item) {
  26. if (isset($this->itemValidator)) {
  27. try {
  28. $this->itemValidator->assert($item);
  29. } catch (ValidationException $e) {
  30. $exceptions[] = $e;
  31. }
  32. }
  33. if (isset($this->keyValidator)) {
  34. try {
  35. $this->keyValidator->assert($key);
  36. } catch (ValidationException $e) {
  37. $exceptions[] = $e;
  38. }
  39. }
  40. }
  41. if (!empty($exceptions)) {
  42. throw $this->reportError($input)->setRelated($exceptions);
  43. }
  44. return true;
  45. }
  46. public function check($input)
  47. {
  48. if (empty($input)) {
  49. return true;
  50. }
  51. if (!is_array($input) || $input instanceof Traversable) {
  52. throw $this->reportError($input);
  53. }
  54. foreach ($input as $key => $item) {
  55. if (isset($this->itemValidator)) {
  56. $this->itemValidator->check($item);
  57. }
  58. if (isset($this->keyValidator)) {
  59. $this->keyValidator->check($key);
  60. }
  61. }
  62. return true;
  63. }
  64. public function validate($input)
  65. {
  66. if (!is_array($input) || $input instanceof Traversable) {
  67. return false;
  68. }
  69. if (empty($input)) {
  70. return true;
  71. }
  72. foreach ($input as $key => $item) {
  73. if (isset($this->itemValidator) && !$this->itemValidator->validate($item)) {
  74. return false;
  75. }
  76. if (isset($this->keyValidator) && !$this->keyValidator->validate($key)) {
  77. return false;
  78. }
  79. }
  80. return true;
  81. }
  82. }