Message.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: oliver
  5. * Date: 26.02.2016
  6. * Time: 22:47
  7. */
  8. class Message
  9. {
  10. const TYPE_FAIL = 'fail';
  11. const TYPE_ERROR = 'fail';
  12. const TYPE_WARNING = 'warning';
  13. const TYPE_SUCCESS = 'success';
  14. /**
  15. * @var Message
  16. */
  17. protected static $instance;
  18. /**
  19. * Holds all messages
  20. *
  21. * @var array
  22. */
  23. protected $messages = array();
  24. private function __construct()
  25. {
  26. }
  27. private function __clone()
  28. {
  29. }
  30. /**
  31. * @return Message
  32. */
  33. public static function getInstance()
  34. {
  35. if(is_null(static::$instance)){
  36. static::$instance = new static();
  37. }
  38. return static::$instance;
  39. }
  40. /**
  41. * Add a new message
  42. *
  43. * @param string $type Supported types: success, fail, info
  44. * @param string $text
  45. */
  46. public function add($type, $text)
  47. {
  48. if(!in_array($type, array(static::TYPE_FAIL, static::TYPE_ERROR, static::TYPE_WARNING, static::TYPE_SUCCESS))){
  49. throw new InvalidArgumentException;
  50. }
  51. $this->messages[] = array(
  52. 'type' => $type,
  53. 'message' => $text,
  54. );
  55. }
  56. /**
  57. * Add a new success message
  58. *
  59. * @param string $text
  60. */
  61. public function fail($text)
  62. {
  63. $this->add(static::TYPE_FAIL, $text);
  64. }
  65. /**
  66. * Add a new success message
  67. *
  68. * @param string $text
  69. */
  70. public function error($text)
  71. {
  72. $this->add(static::TYPE_ERROR, $text);
  73. }
  74. /**
  75. * Add a new success message
  76. *
  77. * @param string $text
  78. */
  79. public function warning($text)
  80. {
  81. $this->add(static::TYPE_WARNING, $text);
  82. }
  83. /**
  84. * Add a new success message
  85. *
  86. * @param string $text
  87. */
  88. public function success($text)
  89. {
  90. $this->add(static::TYPE_SUCCESS, $text);
  91. }
  92. /**
  93. * Render all messages
  94. *
  95. * @param null|string $type null = render all
  96. *
  97. * @return string
  98. */
  99. public function render($type = null)
  100. {
  101. $out = '';
  102. if(count($this->messages) > 0){
  103. $out .= '<div class="notifications">';
  104. foreach($this->messages as $message){
  105. if(is_null($type) || $type == $message['type']){
  106. $out .= '<div class="notification notification-'.$message['type'].'">'.$message['message'].'</div>';
  107. }
  108. }
  109. $out .= '</div>';
  110. }
  111. return $out;
  112. }
  113. }