ObjectDefinition.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Di\Definition;
  12. use Hyperf\Di\ReflectionManager;
  13. class ObjectDefinition implements DefinitionInterface
  14. {
  15. protected ?MethodInjection $constructorInjection = null;
  16. private ?string $className;
  17. private bool $classExists = false;
  18. private bool $instantiable = false;
  19. public function __construct(private string $name, ?string $className = null)
  20. {
  21. $this->setClassName($className ?? $name);
  22. }
  23. public function __toString(): string
  24. {
  25. return sprintf('Object[%s]', $this->getClassName());
  26. }
  27. public function getName(): string
  28. {
  29. return $this->name;
  30. }
  31. public function setName(string $name): self
  32. {
  33. $this->name = $name;
  34. return $this;
  35. }
  36. public function setClassName(?string $className = null): void
  37. {
  38. $this->className = $className;
  39. $this->updateStatusCache();
  40. }
  41. public function getClassName(): string
  42. {
  43. return $this->className ?? $this->name;
  44. }
  45. public function isClassExists(): bool
  46. {
  47. return $this->classExists;
  48. }
  49. public function isInstantiable(): bool
  50. {
  51. return $this->instantiable;
  52. }
  53. /**
  54. * @return null|MethodInjection
  55. */
  56. public function getConstructorInjection()
  57. {
  58. return $this->constructorInjection;
  59. }
  60. public function setConstructorInjection(MethodInjection $injection): self
  61. {
  62. $this->constructorInjection = $injection;
  63. return $this;
  64. }
  65. public function completeConstructorInjection(MethodInjection $injection): void
  66. {
  67. if ($this->constructorInjection !== null) {
  68. // Merge
  69. $this->constructorInjection->merge($injection);
  70. } else {
  71. // Set
  72. $this->constructorInjection = $injection;
  73. }
  74. }
  75. private function updateStatusCache(): void
  76. {
  77. $className = $this->getClassName();
  78. $this->classExists = class_exists($className) || interface_exists($className);
  79. if (! $this->classExists) {
  80. $this->instantiable = false;
  81. return;
  82. }
  83. $this->instantiable = ReflectionManager::reflectClass($className)->isInstantiable();
  84. }
  85. }