Geen omschrijving

Engine.php 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace MailPoetVendor\Sudzy;
  3. if (!defined('ABSPATH')) exit;
  4. /**
  5. * Singleton valdation engine
  6. **/
  7. class Engine
  8. {
  9. /**
  10. * Validation methods are stored here so they can easily be overwritten
  11. */
  12. protected $_checks;
  13. public function __construct() {
  14. $this->_checks = [
  15. 'required' => [$this, '_required'],
  16. 'minLength' => [$this, '_minLength'],
  17. 'maxLength' => [$this, '_maxLength'],
  18. 'isEmail' => [$this, '_isEmail'],
  19. 'isInteger' => [$this, '_isInteger'],
  20. 'isNumeric' => [$this, '_isNumeric'],
  21. ];
  22. }
  23. public function __call($name, $args) {
  24. if (!isset($this->_checks[$name]))
  25. throw new \InvalidArgumentException("{$name} is not a valid validation function.");
  26. $val = array_shift($args);
  27. $args = array_shift($args);
  28. return call_user_func($this->_checks[$name], $val, $args);
  29. }
  30. public function executeOne($check, $val, $params=[]) {
  31. $callback = __NAMESPACE__ . '\Engine::' . $check;
  32. if (is_callable($callback)) {
  33. return call_user_func($callback, $val, $params);
  34. }
  35. }
  36. /**
  37. * @param string $label label used to call function
  38. * @param Callable $function function with params (value, additional params as array)
  39. * @throws \Exception
  40. */
  41. public function addValidator($label, $function) {
  42. if (isset($this->_checks[$label])) throw new \Exception();
  43. $this->setValidator($label, $function);
  44. }
  45. public function setValidator($label, $function) {
  46. $this->_checks[$label] = $function;
  47. }
  48. public function removeValidator($label) {
  49. unset($this->_checks[$label]);
  50. }
  51. /**
  52. * @return array<int, int|string> The list of usable validator methods
  53. */
  54. public function getValidators() {
  55. return array_keys($this->_checks);
  56. }
  57. ///// Validator methods
  58. protected function _isEmail($val, $params) {
  59. return false !== filter_var($val, FILTER_VALIDATE_EMAIL);
  60. }
  61. protected function _isInteger($val, $params) {
  62. if (!is_numeric($val)) return false;
  63. return intval($val) == $val;
  64. }
  65. protected function _isNumeric($val, $params) {
  66. return is_numeric($val);
  67. }
  68. protected function _minLength($val, $params) {
  69. $len = array_shift($params);
  70. return strlen($val) >= $len;
  71. }
  72. protected function _maxLength($val, $params) {
  73. $len = array_shift($params);
  74. return strlen($val) <= $len;
  75. }
  76. protected function _required($val, $params=[]) {
  77. return !(($val === null) || ('' === trim($val)));
  78. }
  79. }