ParameterBag.php 7.5 KB

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