ParameterBag.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation;
  11. use Symfony\Component\HttpFoundation\Exception\BadRequestException;
  12. use Symfony\Component\HttpFoundation\Exception\UnexpectedValueException;
  13. /**
  14. * ParameterBag is a container for key/value pairs.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. *
  18. * @implements \IteratorAggregate<string, mixed>
  19. */
  20. class ParameterBag implements \IteratorAggregate, \Countable
  21. {
  22. public function __construct(
  23. protected array $parameters = [],
  24. ) {
  25. }
  26. /**
  27. * Returns the parameters.
  28. *
  29. * @param string|null $key The name of the parameter to return or null to get them all
  30. */
  31. public function all(?string $key = null): array
  32. {
  33. if (null === $key) {
  34. return $this->parameters;
  35. }
  36. if (!\is_array($value = $this->parameters[$key] ?? [])) {
  37. throw new BadRequestException(\sprintf('Unexpected value for parameter "%s": expecting "array", got "%s".', $key, get_debug_type($value)));
  38. }
  39. return $value;
  40. }
  41. /**
  42. * Returns the parameter keys.
  43. */
  44. public function keys(): array
  45. {
  46. return array_keys($this->parameters);
  47. }
  48. /**
  49. * Replaces the current parameters by a new set.
  50. */
  51. public function replace(array $parameters = []): void
  52. {
  53. $this->parameters = $parameters;
  54. }
  55. /**
  56. * Adds parameters.
  57. */
  58. public function add(array $parameters = []): void
  59. {
  60. $this->parameters = array_replace($this->parameters, $parameters);
  61. }
  62. public function get(string $key, mixed $default = null): mixed
  63. {
  64. return \array_key_exists($key, $this->parameters) ? $this->parameters[$key] : $default;
  65. }
  66. public function set(string $key, mixed $value): void
  67. {
  68. $this->parameters[$key] = $value;
  69. }
  70. /**
  71. * Returns true if the parameter is defined.
  72. */
  73. public function has(string $key): bool
  74. {
  75. return \array_key_exists($key, $this->parameters);
  76. }
  77. /**
  78. * Removes a parameter.
  79. */
  80. public function remove(string $key): void
  81. {
  82. unset($this->parameters[$key]);
  83. }
  84. /**
  85. * Returns the alphabetic characters of the parameter value.
  86. */
  87. public function getAlpha(string $key, string $default = ''): string
  88. {
  89. return preg_replace('/[^[:alpha:]]/', '', $this->getString($key, $default));
  90. }
  91. /**
  92. * Returns the alphabetic characters and digits of the parameter value.
  93. */
  94. public function getAlnum(string $key, string $default = ''): string
  95. {
  96. return preg_replace('/[^[:alnum:]]/', '', $this->getString($key, $default));
  97. }
  98. /**
  99. * Returns the digits of the parameter value.
  100. */
  101. public function getDigits(string $key, string $default = ''): string
  102. {
  103. return preg_replace('/[^[:digit:]]/', '', $this->getString($key, $default));
  104. }
  105. /**
  106. * Returns the parameter as string.
  107. */
  108. public function getString(string $key, string $default = ''): string
  109. {
  110. $value = $this->get($key, $default);
  111. if (!\is_scalar($value) && !$value instanceof \Stringable) {
  112. throw new UnexpectedValueException(\sprintf('Parameter value "%s" cannot be converted to "string".', $key));
  113. }
  114. return (string) $value;
  115. }
  116. /**
  117. * Returns the parameter value converted to integer.
  118. */
  119. public function getInt(string $key, int $default = 0): int
  120. {
  121. return $this->filter($key, $default, \FILTER_VALIDATE_INT, ['flags' => \FILTER_REQUIRE_SCALAR]);
  122. }
  123. /**
  124. * Returns the parameter value converted to boolean.
  125. */
  126. public function getBoolean(string $key, bool $default = false): bool
  127. {
  128. return $this->filter($key, $default, \FILTER_VALIDATE_BOOL, ['flags' => \FILTER_REQUIRE_SCALAR]);
  129. }
  130. /**
  131. * Returns the parameter value converted to an enum.
  132. *
  133. * @template T of \BackedEnum
  134. *
  135. * @param class-string<T> $class
  136. * @param ?T $default
  137. *
  138. * @return ?T
  139. *
  140. * @psalm-return ($default is null ? T|null : T)
  141. */
  142. public function getEnum(string $key, string $class, ?\BackedEnum $default = null): ?\BackedEnum
  143. {
  144. $value = $this->get($key);
  145. if (null === $value) {
  146. return $default;
  147. }
  148. try {
  149. return $class::from($value);
  150. } catch (\ValueError|\TypeError $e) {
  151. throw new UnexpectedValueException(\sprintf('Parameter "%s" cannot be converted to enum: %s.', $key, $e->getMessage()), $e->getCode(), $e);
  152. }
  153. }
  154. /**
  155. * Filter key.
  156. *
  157. * @param int $filter FILTER_* constant
  158. * @param int|array{flags?: int, options?: array} $options Flags from FILTER_* constants
  159. *
  160. * @see https://php.net/filter-var
  161. */
  162. public function filter(string $key, mixed $default = null, int $filter = \FILTER_DEFAULT, mixed $options = []): mixed
  163. {
  164. $value = $this->get($key, $default);
  165. // Always turn $options into an array - this allows filter_var option shortcuts.
  166. if (!\is_array($options) && $options) {
  167. $options = ['flags' => $options];
  168. }
  169. // Add a convenience check for arrays.
  170. if (\is_array($value) && !isset($options['flags'])) {
  171. $options['flags'] = \FILTER_REQUIRE_ARRAY;
  172. }
  173. if (\is_object($value) && !$value instanceof \Stringable) {
  174. throw new UnexpectedValueException(\sprintf('Parameter value "%s" cannot be filtered.', $key));
  175. }
  176. if ((\FILTER_CALLBACK & $filter) && !(($options['options'] ?? null) instanceof \Closure)) {
  177. throw new \InvalidArgumentException(\sprintf('A Closure must be passed to "%s()" when FILTER_CALLBACK is used, "%s" given.', __METHOD__, get_debug_type($options['options'] ?? null)));
  178. }
  179. $options['flags'] ??= 0;
  180. $nullOnFailure = $options['flags'] & \FILTER_NULL_ON_FAILURE;
  181. $options['flags'] |= \FILTER_NULL_ON_FAILURE;
  182. $value = filter_var($value, $filter, $options);
  183. if (null !== $value || $nullOnFailure) {
  184. return $value;
  185. }
  186. throw new \UnexpectedValueException(\sprintf('Parameter value "%s" is invalid and flag "FILTER_NULL_ON_FAILURE" was not set.', $key));
  187. }
  188. /**
  189. * Returns an iterator for parameters.
  190. *
  191. * @return \ArrayIterator<string, mixed>
  192. */
  193. public function getIterator(): \ArrayIterator
  194. {
  195. return new \ArrayIterator($this->parameters);
  196. }
  197. /**
  198. * Returns the number of parameters.
  199. */
  200. public function count(): int
  201. {
  202. return \count($this->parameters);
  203. }
  204. }