Parameters.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. <?php
  2. declare(strict_types=1);
  3. namespace Laminas\Stdlib;
  4. use ArrayObject as PhpArrayObject;
  5. use ReturnTypeWillChange;
  6. use function http_build_query;
  7. use function parse_str;
  8. /**
  9. * @template TKey of array-key
  10. * @template TValue
  11. * @template-extends PhpArrayObject<TKey, TValue>
  12. * @template-implements ParametersInterface<TKey, TValue>
  13. */
  14. class Parameters extends PhpArrayObject implements ParametersInterface
  15. {
  16. /**
  17. * Constructor
  18. *
  19. * Enforces that we have an array, and enforces parameter access to array
  20. * elements.
  21. *
  22. * @param array<TKey, TValue>|null $values
  23. */
  24. public function __construct(?array $values = null)
  25. {
  26. if (null === $values) {
  27. $values = [];
  28. }
  29. parent::__construct($values, ArrayObject::ARRAY_AS_PROPS);
  30. }
  31. /**
  32. * Populate from native PHP array
  33. *
  34. * @param array<TKey, TValue> $values
  35. * @return void
  36. */
  37. public function fromArray(array $values)
  38. {
  39. $this->exchangeArray($values);
  40. }
  41. /**
  42. * Populate from query string
  43. *
  44. * @param string $string
  45. * @return void
  46. */
  47. public function fromString($string)
  48. {
  49. $array = [];
  50. parse_str($string, $array);
  51. $this->fromArray($array);
  52. }
  53. /**
  54. * Serialize to native PHP array
  55. *
  56. * @return array<TKey, TValue>
  57. */
  58. public function toArray()
  59. {
  60. return $this->getArrayCopy();
  61. }
  62. /**
  63. * Serialize to query string
  64. *
  65. * @return string
  66. */
  67. public function toString()
  68. {
  69. return http_build_query($this->toArray());
  70. }
  71. /**
  72. * Retrieve by key
  73. *
  74. * Returns null if the key does not exist.
  75. *
  76. * @param TKey $name
  77. * @return TValue|null
  78. */
  79. #[ReturnTypeWillChange]
  80. public function offsetGet($name)
  81. {
  82. if ($this->offsetExists($name)) {
  83. return parent::offsetGet($name);
  84. }
  85. return null;
  86. }
  87. /**
  88. * @template TDefault
  89. * @param TKey $name
  90. * @param TDefault $default optional default value
  91. * @return TValue|TDefault|null
  92. */
  93. public function get($name, $default = null)
  94. {
  95. if ($this->offsetExists($name)) {
  96. return parent::offsetGet($name);
  97. }
  98. return $default;
  99. }
  100. /**
  101. * @param TKey $name
  102. * @param TValue $value
  103. * @return $this
  104. */
  105. public function set($name, $value)
  106. {
  107. $this[$name] = $value;
  108. return $this;
  109. }
  110. }