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