ParameterBagUtils.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. * @param ParameterBag $parameters The parameter bag
  28. * @param string $path The key
  29. *
  30. * @return mixed
  31. *
  32. * @throws InvalidArgumentException when the given path is malformed
  33. */
  34. public static function getParameterBagValue(ParameterBag $parameters, $path)
  35. {
  36. if (false === $pos = strpos($path, '[')) {
  37. return $parameters->get($path);
  38. }
  39. $root = substr($path, 0, $pos);
  40. if (null === $value = $parameters->get($root)) {
  41. return;
  42. }
  43. if (null === self::$propertyAccessor) {
  44. self::$propertyAccessor = PropertyAccess::createPropertyAccessor();
  45. }
  46. try {
  47. return self::$propertyAccessor->getValue($value, substr($path, $pos));
  48. } catch (AccessException $e) {
  49. return;
  50. }
  51. }
  52. /**
  53. * Returns a request "parameter" value.
  54. *
  55. * Paths like foo[bar] will be evaluated to find deeper items in nested data structures.
  56. *
  57. * @param Request $request The request
  58. * @param string $path The key
  59. *
  60. * @return mixed
  61. *
  62. * @throws InvalidArgumentException when the given path is malformed
  63. */
  64. public static function getRequestParameterValue(Request $request, $path)
  65. {
  66. if (false === $pos = strpos($path, '[')) {
  67. return $request->get($path);
  68. }
  69. $root = substr($path, 0, $pos);
  70. if (null === $value = $request->get($root)) {
  71. return;
  72. }
  73. if (null === self::$propertyAccessor) {
  74. self::$propertyAccessor = PropertyAccess::createPropertyAccessor();
  75. }
  76. try {
  77. return self::$propertyAccessor->getValue($value, substr($path, $pos));
  78. } catch (AccessException $e) {
  79. return;
  80. }
  81. }
  82. }