error_collector.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php namespace System\Validation;
  2. class Error_Collector {
  3. /**
  4. * All of the error messages.
  5. *
  6. * @var array
  7. */
  8. public $messages;
  9. /**
  10. * Create a new Error Collector instance.
  11. *
  12. * @return void
  13. */
  14. public function __construct($messages = array())
  15. {
  16. $this->messages = $messages;
  17. }
  18. /**
  19. * Add an error message to the collector.
  20. *
  21. * @param string $attribute
  22. * @param string $message
  23. * @return void
  24. */
  25. public function add($attribute, $message)
  26. {
  27. $this->messages[$attribute][] = $message;
  28. }
  29. /**
  30. * Determine if errors exist for an attribute.
  31. *
  32. * @param string $attribute
  33. * @return bool
  34. */
  35. public function has($attribute)
  36. {
  37. return $this->first($attribute) !== '';
  38. }
  39. /**
  40. * Get the first error message for an attribute.
  41. *
  42. * @param string $attribute
  43. * @return string
  44. */
  45. public function first($attribute)
  46. {
  47. return (count($messages = $this->get($attribute)) > 0) ? $messages[0] : '';
  48. }
  49. /**
  50. * Get all of the error messages for an attribute.
  51. *
  52. * If no attribute is specified, all of the error messages will be returned.
  53. *
  54. * @param string $attribute
  55. * @return array
  56. */
  57. public function get($attribute = null)
  58. {
  59. if (is_null($attribute))
  60. {
  61. $all = array();
  62. foreach ($this->messages as $messages)
  63. {
  64. $all = array_merge($all, $messages);
  65. }
  66. return $all;
  67. }
  68. return (array_key_exists($attribute, $this->messages)) ? $this->messages[$attribute] : array();
  69. }
  70. }