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.

65 lines
1.7 KiB

  1. <?php
  2. /**
  3. * @copyright NetMonsters <team@netmonsters.ru>
  4. * @link http://netmonsters.ru
  5. * @package Majestic
  6. * @subpackage validator
  7. * @since 2010-04-24
  8. */
  9. abstract class Validator implements iValidator
  10. {
  11. protected $value;
  12. protected $message;
  13. protected $vars = array();
  14. protected $templates = array();
  15. public function getMessage()
  16. {
  17. return $this->message;
  18. }
  19. protected function setValue($value)
  20. {
  21. $this->value = (string) $value;
  22. $this->message = null;
  23. }
  24. public function setMessage($message, $key = null)
  25. {
  26. if ($key === null) {
  27. $key = current(array_keys($this->templates));
  28. }
  29. $this->templates[$key] = $message;
  30. }
  31. protected function error($template = null, $value = null)
  32. {
  33. if ($template === null) {
  34. $template = current(array_keys($this->templates));
  35. }
  36. if ($value === null) {
  37. $value = $this->value;
  38. }
  39. $this->message = $this->createMessage($template, $value);
  40. }
  41. protected function createMessage($template, $value)
  42. {
  43. if (!isset($this->templates[$template])) {
  44. throw new GeneralException('Message template "' . $template . '" unknown.');
  45. }
  46. $message = $this->templates[$template];
  47. if (strpos($message, '%') !== false) {
  48. $message = str_replace('%value%', (string) $value, $message);
  49. foreach ($this->vars as $property) {
  50. if (property_exists($this, $property)) {
  51. $message = str_replace("%$property%", (string) $this->$property, $message);
  52. }
  53. }
  54. }
  55. return $message;
  56. }
  57. }