ParameterBag.php 6.9 KB

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