Message.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. declare(strict_types=1);
  3. namespace Laminas\Stdlib;
  4. use Traversable;
  5. use function array_key_exists;
  6. use function get_debug_type;
  7. use function is_array;
  8. use function is_scalar;
  9. use function sprintf;
  10. class Message implements MessageInterface
  11. {
  12. /** @var array */
  13. protected $metadata = [];
  14. /** @var mixed */
  15. protected $content = '';
  16. /**
  17. * Set message metadata
  18. *
  19. * Non-destructive setting of message metadata; always adds to the metadata, never overwrites
  20. * the entire metadata container.
  21. *
  22. * @param string|int|array|Traversable $spec
  23. * @param mixed $value
  24. * @throws Exception\InvalidArgumentException
  25. * @return Message
  26. */
  27. public function setMetadata($spec, $value = null)
  28. {
  29. if (is_scalar($spec)) {
  30. $this->metadata[$spec] = $value;
  31. return $this;
  32. }
  33. if (! is_array($spec) && ! $spec instanceof Traversable) {
  34. throw new Exception\InvalidArgumentException(sprintf(
  35. 'Expected a string, array, or Traversable argument in first position; received "%s"',
  36. get_debug_type($spec)
  37. ));
  38. }
  39. foreach ($spec as $key => $value) {
  40. $this->metadata[$key] = $value;
  41. }
  42. return $this;
  43. }
  44. /**
  45. * Retrieve all metadata or a single metadatum as specified by key
  46. *
  47. * @param null|string|int $key
  48. * @param null|mixed $default
  49. * @throws Exception\InvalidArgumentException
  50. * @return mixed
  51. */
  52. public function getMetadata($key = null, $default = null)
  53. {
  54. if (null === $key) {
  55. return $this->metadata;
  56. }
  57. if (! is_scalar($key)) {
  58. throw new Exception\InvalidArgumentException('Non-scalar argument provided for key');
  59. }
  60. if (array_key_exists($key, $this->metadata)) {
  61. return $this->metadata[$key];
  62. }
  63. return $default;
  64. }
  65. /**
  66. * Set message content
  67. *
  68. * @param mixed $value
  69. * @return Message
  70. */
  71. public function setContent($value)
  72. {
  73. $this->content = $value;
  74. return $this;
  75. }
  76. /**
  77. * Get message content
  78. *
  79. * @return mixed
  80. */
  81. public function getContent()
  82. {
  83. return $this->content;
  84. }
  85. /**
  86. * @return string
  87. */
  88. public function toString()
  89. {
  90. $request = '';
  91. foreach ($this->getMetadata() as $key => $value) {
  92. $request .= sprintf(
  93. "%s: %s\r\n",
  94. (string) $key,
  95. (string) $value
  96. );
  97. }
  98. $request .= "\r\n" . $this->getContent();
  99. return $request;
  100. }
  101. }