Util.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace Illuminate\Container;
  3. use Closure;
  4. use Illuminate\Contracts\Container\ContextualAttribute;
  5. use ReflectionAttribute;
  6. use ReflectionNamedType;
  7. /**
  8. * @internal
  9. */
  10. class Util
  11. {
  12. /**
  13. * If the given value is not an array and not null, wrap it in one.
  14. *
  15. * From Arr::wrap() in Illuminate\Support.
  16. *
  17. * @param mixed $value
  18. * @return array
  19. */
  20. public static function arrayWrap($value)
  21. {
  22. if (is_null($value)) {
  23. return [];
  24. }
  25. return is_array($value) ? $value : [$value];
  26. }
  27. /**
  28. * Return the default value of the given value.
  29. *
  30. * From global value() helper in Illuminate\Support.
  31. *
  32. * @param mixed $value
  33. * @param mixed ...$args
  34. * @return mixed
  35. */
  36. public static function unwrapIfClosure($value, ...$args)
  37. {
  38. return $value instanceof Closure ? $value(...$args) : $value;
  39. }
  40. /**
  41. * Get the class name of the given parameter's type, if possible.
  42. *
  43. * From Reflector::getParameterClassName() in Illuminate\Support.
  44. *
  45. * @param \ReflectionParameter $parameter
  46. * @return string|null
  47. */
  48. public static function getParameterClassName($parameter)
  49. {
  50. $type = $parameter->getType();
  51. if (! $type instanceof ReflectionNamedType || $type->isBuiltin()) {
  52. return null;
  53. }
  54. $name = $type->getName();
  55. if (! is_null($class = $parameter->getDeclaringClass())) {
  56. if ($name === 'self') {
  57. return $class->getName();
  58. }
  59. if ($name === 'parent' && $parent = $class->getParentClass()) {
  60. return $parent->getName();
  61. }
  62. }
  63. return $name;
  64. }
  65. /**
  66. * Get a contextual attribute from a dependency.
  67. *
  68. * @param \ReflectionParameter $dependency
  69. * @return \ReflectionAttribute|null
  70. */
  71. public static function getContextualAttributeFromDependency($dependency)
  72. {
  73. return $dependency->getAttributes(ContextualAttribute::class, ReflectionAttribute::IS_INSTANCEOF)[0] ?? null;
  74. }
  75. }