ParameterBagUtils.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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\Security\Http;
  11. use Symfony\Component\HttpFoundation\ParameterBag;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\PropertyAccess\Exception\AccessException;
  14. use Symfony\Component\PropertyAccess\Exception\InvalidArgumentException;
  15. use Symfony\Component\PropertyAccess\PropertyAccess;
  16. /**
  17. * @internal
  18. */
  19. final class ParameterBagUtils
  20. {
  21. private static $propertyAccessor;
  22. /**
  23. * Returns a "parameter" value.
  24. *
  25. * Paths like foo[bar] will be evaluated to find deeper items in nested data structures.
  26. *
  27. * @return mixed
  28. *
  29. * @throws InvalidArgumentException when the given path is malformed
  30. */
  31. public static function getParameterBagValue(ParameterBag $parameters, string $path)
  32. {
  33. if (false === $pos = strpos($path, '[')) {
  34. return $parameters->all()[$path] ?? null;
  35. }
  36. $root = substr($path, 0, $pos);
  37. if (null === $value = $parameters->all()[$root] ?? null) {
  38. return null;
  39. }
  40. if (null === self::$propertyAccessor) {
  41. self::$propertyAccessor = PropertyAccess::createPropertyAccessor();
  42. }
  43. try {
  44. return self::$propertyAccessor->getValue($value, substr($path, $pos));
  45. } catch (AccessException $e) {
  46. return null;
  47. }
  48. }
  49. /**
  50. * Returns a request "parameter" value.
  51. *
  52. * Paths like foo[bar] will be evaluated to find deeper items in nested data structures.
  53. *
  54. * @return mixed
  55. *
  56. * @throws InvalidArgumentException when the given path is malformed
  57. */
  58. public static function getRequestParameterValue(Request $request, string $path)
  59. {
  60. if (false === $pos = strpos($path, '[')) {
  61. return $request->get($path);
  62. }
  63. $root = substr($path, 0, $pos);
  64. if (null === $value = $request->get($root)) {
  65. return null;
  66. }
  67. if (null === self::$propertyAccessor) {
  68. self::$propertyAccessor = PropertyAccess::createPropertyAccessor();
  69. }
  70. try {
  71. return self::$propertyAccessor->getValue($value, substr($path, $pos));
  72. } catch (AccessException $e) {
  73. return null;
  74. }
  75. }
  76. }