StockLevels.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. *
  4. * PHP Pro Bid $Id$ CIRslYEf3mfCjDYVWa6h00QEiY+aTS/CqM7LtuIw6fY=
  5. *
  6. * @link http://www.phpprobid.com
  7. * @copyright Copyright (c) 2016 Online Ventures Software & CodeCube SRL
  8. * @license http://www.phpprobid.com/license Commercial License
  9. *
  10. * @version 7.8
  11. */
  12. /**
  13. * stock levels field validator class
  14. */
  15. namespace Ppb\Validate;
  16. use Cube\Validate\AbstractValidate,
  17. Ppb\Form\Element\StockLevels as StockLevelsElement;
  18. class StockLevels extends AbstractValidate
  19. {
  20. const NO_STOCK = 1;
  21. const QUANTITY_NOT_NUMERIC = 2;
  22. const PRICE_NOT_NUMERIC = 3;
  23. protected $_messages = array(
  24. self::NO_STOCK => "'%s' is required and cannot be empty.",
  25. self::QUANTITY_NOT_NUMERIC => "'%s': the quantity fields only accept positive integer values.",
  26. self::PRICE_NOT_NUMERIC => "'%s': the price fields only accept numeric values.",
  27. );
  28. /**
  29. *
  30. * checks if at least one stock option has been entered and
  31. * if the price fields contain numeric values
  32. *
  33. * @return bool return true if the validation is successful
  34. */
  35. public function isValid()
  36. {
  37. $value = $this->getValue();
  38. $array = array();
  39. if (is_array($value)) {
  40. foreach ($value as $k => $v) {
  41. $array[StockLevelsElement::FIELD_OPTIONS][] = $v[StockLevelsElement::FIELD_OPTIONS];
  42. $array[StockLevelsElement::FIELD_PRICE][] = $v[StockLevelsElement::FIELD_PRICE];
  43. $array[StockLevelsElement::FIELD_QUANTITY][] = $v[StockLevelsElement::FIELD_QUANTITY];
  44. }
  45. $value = $array;
  46. if (isset($value[StockLevelsElement::FIELD_OPTIONS])) {
  47. $values = array_filter($value[StockLevelsElement::FIELD_OPTIONS]);
  48. if (count($values) > 0) {
  49. $prices = array_filter($value[StockLevelsElement::FIELD_PRICE]);
  50. foreach ($prices as $price) {
  51. if (!is_numeric($price)) {
  52. $this->setMessage($this->_messages[self::PRICE_NOT_NUMERIC]);
  53. return false;
  54. }
  55. }
  56. $quantities = array_filter($value[StockLevelsElement::FIELD_QUANTITY], function($val) {
  57. return ($val !== null && $val !== false && $val !== '');
  58. });
  59. foreach ($quantities as $quantity) {
  60. if (!preg_match('#^[0-9]+$#', $quantity)) {
  61. $this->setMessage($this->_messages[self::QUANTITY_NOT_NUMERIC]);
  62. return false;
  63. }
  64. }
  65. if (count($quantities) > 0) {
  66. return true;
  67. }
  68. }
  69. $this->setMessage($this->_messages[self::NO_STOCK]);
  70. return false;
  71. }
  72. }
  73. return true;
  74. }
  75. }