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.

64 lines
1.6 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. * @version SVN: $Id$
  9. * @filesource $URL$
  10. */
  11. abstract class Validator implements iValidator
  12. {
  13. protected $value;
  14. protected $message;
  15. protected $vars = array();
  16. protected $templates = array();
  17. public function getMessage()
  18. {
  19. return $this->message;
  20. }
  21. protected function setValue($value)
  22. {
  23. $this->value = (string) $value;
  24. $this->message = null;
  25. }
  26. public function setMessage($key, $message)
  27. {
  28. $this->templates[$key] = $message;
  29. }
  30. protected function error($template = null, $value = null)
  31. {
  32. if ($template === null) {
  33. $template = current(array_keys($this->templates));
  34. }
  35. if ($value === null) {
  36. $value = $this->value;
  37. }
  38. $this->message = $this->createMessage($template, $value);
  39. }
  40. protected function createMessage($template, $value)
  41. {
  42. if (!isset($this->templates[$template])) {
  43. throw new Exception('Message template "' . $template . '" unknown.');
  44. }
  45. $message = $this->templates[$template];
  46. if (strpos($message, '%') !== false) {
  47. $message = str_replace('%value%', (string) $value, $message);
  48. foreach ($this->vars as $property) {
  49. if (property_exists($this, $property)) {
  50. $message = str_replace("%$property%", (string) $this->$property, $message);
  51. }
  52. }
  53. }
  54. return $message;
  55. }
  56. }