You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

118 lines
2.8 KiB

  1. <?php
  2. /**
  3. * @copyright NetMonsters <team@netmonsters.ru>
  4. * @link http://netmonsters.ru
  5. * @package Majestic
  6. * @subpackage form
  7. * @since 2010-04-24
  8. * @version SVN: $Id$
  9. * @filesource $URL$
  10. */
  11. abstract class Form
  12. {
  13. const SUCCESS = 'success';
  14. const ERROR = 'error';
  15. protected $fields = array();
  16. protected $messages = array(self::SUCCESS => 'Form data valid',
  17. self::ERROR => 'Form data invalid');
  18. protected $valid = true;
  19. public function __construct()
  20. {
  21. $this->init();
  22. }
  23. /**
  24. * @param string $name
  25. * @return FormField
  26. */
  27. protected function addField($name, $message = false)
  28. {
  29. $this->fields[$name] = new FormField($message);
  30. return $this->fields[$name];
  31. }
  32. public function isValid($data)
  33. {
  34. if (!is_array($data)) {
  35. throw new Exception(__CLASS__ . '::' . __METHOD__ . ' expects an array');
  36. }
  37. foreach ($this->fields as $field_name => $field) {
  38. if (isset($data[$field_name])) {
  39. $this->valid &= $field->isValid($data[$field_name], $data);
  40. } else {
  41. $this->valid &= $field->isValid(null, $data);
  42. }
  43. }
  44. if (!$this->valid) {
  45. $this->fillHelperData();
  46. }
  47. return $this->valid;
  48. }
  49. public function getMessages()
  50. {
  51. $messages = array();
  52. foreach ($this->fields as $name => $field) {
  53. if ($mess = $field->getMessage()) {
  54. $messages[$name] = $mess;
  55. }
  56. }
  57. return $messages;
  58. }
  59. public function getValues()
  60. {
  61. $values = array();
  62. foreach ($this->fields as $key => $field) {
  63. if (!$field->isIgnored()) {
  64. $values[$key] = $field->getValue();
  65. }
  66. }
  67. return $values;
  68. }
  69. public function getSourceValues()
  70. {
  71. $values = array();
  72. foreach ($this->fields as $key => $field) {
  73. $values[$key] = $field->getSourceValue();
  74. }
  75. return $values;
  76. }
  77. public function getMessageType()
  78. {
  79. return ($this->valid) ? self::SUCCESS : self::ERROR;
  80. }
  81. public function getMessage()
  82. {
  83. return $this->messages[$this->getMessageType()];
  84. }
  85. public function setSuccessMessage($message)
  86. {
  87. $this->messages[self::SUCCESS] = (string) $message;
  88. return $this;
  89. }
  90. public function setErrorMessage($message)
  91. {
  92. $this->messages[self::ERROR] = (string) $message;
  93. return $this;
  94. }
  95. protected function fillHelperData()
  96. {
  97. $data['messages'] = $this->getMessages();
  98. $data['values'] = $this->getSourceValues();
  99. Session::set(get_class($this), $data);
  100. }
  101. abstract protected function init();
  102. }