AbstractLazyProxyBuilder.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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\LazyLoader;
  12. use PhpParser\BuilderFactory;
  13. use PhpParser\Node;
  14. use PhpParser\Node\Const_;
  15. use PhpParser\Node\Scalar\String_;
  16. use PhpParser\Node\Stmt\ClassConst;
  17. use function Hyperf\Support\class_basename;
  18. abstract class AbstractLazyProxyBuilder
  19. {
  20. /**
  21. * The Builder instance.
  22. * @var mixed
  23. */
  24. public $builder;
  25. /**
  26. * The BuilderFactory.
  27. */
  28. public BuilderFactory $factory;
  29. /**
  30. * Class Namespace.
  31. */
  32. protected ?string $namespace = null;
  33. protected ?string $proxyClassName = null;
  34. protected ?string $originalClassName = null;
  35. public function __construct()
  36. {
  37. $this->factory = new BuilderFactory();
  38. $this->builder = $this->factory;
  39. }
  40. abstract public function addClassRelationship(): AbstractLazyProxyBuilder;
  41. public function addClassBoilerplate(string $proxyClassName, string $originalClassName): AbstractLazyProxyBuilder
  42. {
  43. $namespace = join('\\', array_slice(explode('\\', $proxyClassName), 0, -1));
  44. $this->namespace = $namespace;
  45. $this->proxyClassName = $proxyClassName;
  46. $this->originalClassName = $originalClassName;
  47. $this->builder = $this->factory->class(class_basename($proxyClassName))
  48. ->addStmt(new ClassConst([new Const_('PROXY_TARGET', new String_($originalClassName))]))
  49. ->addStmt($this->factory->useTrait('\Hyperf\Di\LazyLoader\LazyProxyTrait'))
  50. ->setDocComment("/**
  51. * Be careful: This is a lazy proxy, not the real {$originalClassName} from container.
  52. *
  53. * {@inheritdoc}
  54. */");
  55. return $this;
  56. }
  57. public function addNodes(array $nodes): AbstractLazyProxyBuilder
  58. {
  59. foreach ($nodes as $stmt) {
  60. $this->builder = $this->builder->addStmt($stmt);
  61. }
  62. return $this;
  63. }
  64. public function getNode(): Node
  65. {
  66. if ($this->namespace) {
  67. return $this->factory
  68. ->namespace($this->namespace)
  69. ->addStmt($this->builder)
  70. ->getNode();
  71. }
  72. return $this->builder->getNode();
  73. }
  74. public function getNamespace(): string
  75. {
  76. return $this->namespace;
  77. }
  78. public function getProxyClassName(): string
  79. {
  80. return $this->proxyClassName;
  81. }
  82. public function getOriginalClassName(): string
  83. {
  84. return $this->originalClassName;
  85. }
  86. }