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.

67 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. * @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($message, $key = null)
  27. {
  28. if ($key === null) {
  29. $key = current(array_keys($this->templates));
  30. }
  31. $this->templates[$key] = $message;
  32. }
  33. protected function error($template = null, $value = null)
  34. {
  35. if ($template === null) {
  36. $template = current(array_keys($this->templates));
  37. }
  38. if ($value === null) {
  39. $value = $this->value;
  40. }
  41. $this->message = $this->createMessage($template, $value);
  42. }
  43. protected function createMessage($template, $value)
  44. {
  45. if (!isset($this->templates[$template])) {
  46. throw new Exception('Message template "' . $template . '" unknown.');
  47. }
  48. $message = $this->templates[$template];
  49. if (strpos($message, '%') !== false) {
  50. $message = str_replace('%value%', (string) $value, $message);
  51. foreach ($this->vars as $property) {
  52. if (property_exists($this, $property)) {
  53. $message = str_replace("%$property%", (string) $this->$property, $message);
  54. }
  55. }
  56. }
  57. return $message;
  58. }
  59. }