Validate.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. <?php
  2. /**
  3. *
  4. * Cube Framework $Id$ 6RN/6vfYQnm3fREMggMTV3wSnHQ8y1YJAc7maH9DV0s=
  5. *
  6. * @link http://codecu.be/framework
  7. * @copyright Copyright (c) 2015 CodeCube SRL
  8. * @license http://codecu.be/framework/license Commercial License
  9. *
  10. * @version 1.6
  11. */
  12. namespace Cube\View\Helper;
  13. use Cube\Validate\AbstractValidate;
  14. class Validate extends AbstractHelper
  15. {
  16. /**
  17. * validator object
  18. *
  19. * @var \Cube\Validate\AbstractValidate
  20. */
  21. protected $_validator;
  22. /**
  23. *
  24. * get validator
  25. *
  26. * @return \Cube\Validate\AbstractValidate
  27. *
  28. * @throws \InvalidArgumentException
  29. */
  30. public function getValidator()
  31. {
  32. if (!$this->_validator instanceof AbstractValidate) {
  33. throw new \InvalidArgumentException("A validator has not been initialized.");
  34. }
  35. return $this->_validator;
  36. }
  37. /**
  38. *
  39. * set validator object
  40. *
  41. * @param \Cube\Validate\AbstractValidate $validator
  42. *
  43. * @return $this
  44. */
  45. public function setValidator(AbstractValidate $validator)
  46. {
  47. $this->_validator = $validator;
  48. return $this;
  49. }
  50. /**
  51. *
  52. * direct method, callable from within the view to return the helper
  53. *
  54. * @return $this
  55. */
  56. public function validate(AbstractValidate $validator = null)
  57. {
  58. if ($validator instanceof AbstractValidate) {
  59. $this->setValidator($validator);
  60. }
  61. return $this;
  62. }
  63. /**
  64. *
  65. * call validator is valid method
  66. *
  67. * @param mixed $value
  68. *
  69. * @return bool
  70. */
  71. public function isValid($value)
  72. {
  73. $validator = $this->getValidator();
  74. $validator->setValue($value);
  75. return @$validator->isValid();
  76. }
  77. /**
  78. *
  79. * call magic method, calls validators and runs them directly
  80. *
  81. * @param string $name
  82. * @param array $arguments
  83. *
  84. * @return bool
  85. */
  86. public function __call($name, $arguments)
  87. {
  88. $className = '\\Cube\\Validate\\' . ucfirst($name);
  89. /** @var \Cube\Validate\AbstractValidate $validator */
  90. if (class_exists($className)) {
  91. $this->setValidator(
  92. new $className());
  93. }
  94. if (count($arguments) == 1) {
  95. $arguments = $arguments[0];
  96. }
  97. return $this->isValid($arguments);
  98. }
  99. }