ArgumentMetadata.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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\HttpKernel\ControllerMetadata;
  11. /**
  12. * Responsible for storing metadata of an argument.
  13. *
  14. * @author Iltar van der Berg <kjarli@gmail.com>
  15. */
  16. class ArgumentMetadata
  17. {
  18. private $name;
  19. private $type;
  20. private $isVariadic;
  21. private $hasDefaultValue;
  22. private $defaultValue;
  23. private $isNullable;
  24. public function __construct(string $name, ?string $type, bool $isVariadic, bool $hasDefaultValue, $defaultValue, bool $isNullable = false)
  25. {
  26. $this->name = $name;
  27. $this->type = $type;
  28. $this->isVariadic = $isVariadic;
  29. $this->hasDefaultValue = $hasDefaultValue;
  30. $this->defaultValue = $defaultValue;
  31. $this->isNullable = $isNullable || null === $type || ($hasDefaultValue && null === $defaultValue);
  32. }
  33. /**
  34. * Returns the name as given in PHP, $foo would yield "foo".
  35. *
  36. * @return string
  37. */
  38. public function getName()
  39. {
  40. return $this->name;
  41. }
  42. /**
  43. * Returns the type of the argument.
  44. *
  45. * The type is the PHP class in 5.5+ and additionally the basic type in PHP 7.0+.
  46. *
  47. * @return string
  48. */
  49. public function getType()
  50. {
  51. return $this->type;
  52. }
  53. /**
  54. * Returns whether the argument is defined as "...$variadic".
  55. *
  56. * @return bool
  57. */
  58. public function isVariadic()
  59. {
  60. return $this->isVariadic;
  61. }
  62. /**
  63. * Returns whether the argument has a default value.
  64. *
  65. * Implies whether an argument is optional.
  66. *
  67. * @return bool
  68. */
  69. public function hasDefaultValue()
  70. {
  71. return $this->hasDefaultValue;
  72. }
  73. /**
  74. * Returns whether the argument accepts null values.
  75. *
  76. * @return bool
  77. */
  78. public function isNullable()
  79. {
  80. return $this->isNullable;
  81. }
  82. /**
  83. * Returns the default value of the argument.
  84. *
  85. * @throws \LogicException if no default value is present; {@see self::hasDefaultValue()}
  86. *
  87. * @return mixed
  88. */
  89. public function getDefaultValue()
  90. {
  91. if (!$this->hasDefaultValue) {
  92. throw new \LogicException(sprintf('Argument $%s does not have a default value. Use %s::hasDefaultValue() to avoid this exception.', $this->name, __CLASS__));
  93. }
  94. return $this->defaultValue;
  95. }
  96. }