ArgsStub.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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\VarDumper\Caster;
  11. use Symfony\Component\VarDumper\Cloner\Stub;
  12. /**
  13. * Represents a list of function arguments.
  14. *
  15. * @author Nicolas Grekas <p@tchwork.com>
  16. */
  17. class ArgsStub extends EnumStub
  18. {
  19. private static $parameters = [];
  20. public function __construct(array $args, string $function, ?string $class)
  21. {
  22. list($variadic, $params) = self::getParameters($function, $class);
  23. $values = [];
  24. foreach ($args as $k => $v) {
  25. $values[$k] = !is_scalar($v) && !$v instanceof Stub ? new CutStub($v) : $v;
  26. }
  27. if (null === $params) {
  28. parent::__construct($values, false);
  29. return;
  30. }
  31. if (\count($values) < \count($params)) {
  32. $params = \array_slice($params, 0, \count($values));
  33. } elseif (\count($values) > \count($params)) {
  34. $values[] = new EnumStub(array_splice($values, \count($params)), false);
  35. $params[] = $variadic;
  36. }
  37. if (['...'] === $params) {
  38. $this->dumpKeys = false;
  39. $this->value = $values[0]->value;
  40. } else {
  41. $this->value = array_combine($params, $values);
  42. }
  43. }
  44. private static function getParameters($function, $class)
  45. {
  46. if (isset(self::$parameters[$k = $class.'::'.$function])) {
  47. return self::$parameters[$k];
  48. }
  49. try {
  50. $r = null !== $class ? new \ReflectionMethod($class, $function) : new \ReflectionFunction($function);
  51. } catch (\ReflectionException $e) {
  52. return [null, null];
  53. }
  54. $variadic = '...';
  55. $params = [];
  56. foreach ($r->getParameters() as $v) {
  57. $k = '$'.$v->name;
  58. if ($v->isPassedByReference()) {
  59. $k = '&'.$k;
  60. }
  61. if ($v->isVariadic()) {
  62. $variadic .= $k;
  63. } else {
  64. $params[] = $k;
  65. }
  66. }
  67. return self::$parameters[$k] = [$variadic, $params];
  68. }
  69. }