NumberValidator.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /* * ********************************************************************
  3. * ProxmoxAddon product developed. (Aug 23, 2018)
  4. * *
  5. *
  6. * CREATED BY MODULESGARDEN -> http://modulesgarden.com
  7. * CONTACT -> contact@modulesgarden.com
  8. *
  9. *
  10. * This software is furnished under a license and may be used and copied
  11. * only in accordance with the terms of such license and with the
  12. * inclusion of the above copyright notice. This software or any other
  13. * copies thereof may not be provided or otherwise made available to any
  14. * other person. No title to and ownership of the software is hereby
  15. * transferred.
  16. *
  17. *
  18. * ******************************************************************** */
  19. namespace ModulesGarden\ProxmoxAddon\App\UI\Validators;
  20. use ModulesGarden\ProxmoxAddon\Core\UI\Widget\Forms\Validators\BaseValidator;
  21. /**
  22. * Description of NumberValidator
  23. *
  24. * @author Pawel Kopec <pawelk@modulesgardne.com>
  25. */
  26. class NumberValidator extends BaseValidator
  27. {
  28. protected $minValue = 0;
  29. protected $maxValue = 0;
  30. protected $required = false;
  31. public function __construct($min = 0, $max = 0, $required = false)
  32. {
  33. $this->minValue = (int)$min;
  34. $this->maxValue = $max;
  35. $this->required = $required;
  36. }
  37. protected function validate($data, $additionalData = null)
  38. {
  39. if (!$this->required && empty($data))
  40. {
  41. return true;
  42. }
  43. if (is_numeric($data) && $this->minValue === 0 && $this->maxValue === 0)
  44. {
  45. return true;
  46. }
  47. //Min & Max
  48. if (is_numeric($data) && $this->minValue <= ((int)$data) && ((int)$data) <= $this->maxValue)
  49. {
  50. return true;
  51. }
  52. //Min
  53. else
  54. {
  55. if (is_numeric($data) && !is_numeric($this->maxValue) && $this->minValue <= ((int)$data))
  56. {
  57. return true;
  58. }
  59. }
  60. if ($this->minValue === $this->maxValue)
  61. {
  62. $this->addValidationError('PleaseProvideANumericValue');
  63. return false;
  64. }
  65. if (is_numeric($this->minValue) && is_numeric($this->maxValue))
  66. {
  67. $this->addValidationError('PleaseProvideANumericValueBetween', false, ['minValue' => $this->minValue, 'maxValue' => $this->maxValue]);
  68. }
  69. else
  70. {
  71. if (is_numeric($this->minValue) && !is_numeric($this->maxValue))
  72. {
  73. $this->addValidationError('PleaseProvideANumericValueFrom', false, ['minValue' => $this->minValue]);
  74. }
  75. }
  76. return false;
  77. }
  78. }