CatchBuild.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. <?php
  2. namespace catcher\generate\build;
  3. use catcher\CatchAdmin;
  4. use catcher\facade\FileSystem;
  5. use catcher\generate\build\classes\Classes;
  6. use PhpParser\BuilderFactory;
  7. use PhpParser\PrettyPrinter\Standard;
  8. class CatchBuild
  9. {
  10. protected $astBuilder;
  11. protected $outPath;
  12. protected $filename;
  13. public function __construct()
  14. {
  15. $this->astBuilder = app(BuilderFactory::class);
  16. }
  17. /**
  18. * 命名空间
  19. *
  20. * @time 2020年11月19日
  21. * @param string $namespace
  22. * @return $this
  23. */
  24. public function namespace(string $namespace)
  25. {
  26. $this->astBuilder = $this->astBuilder->namespace($namespace);
  27. return $this;
  28. }
  29. /**
  30. * use 方法体
  31. *
  32. * @time 2020年11月19日
  33. * @param $use
  34. * @return $this
  35. */
  36. public function use($use)
  37. {
  38. $this->astBuilder->addStmt($use);
  39. return $this;
  40. }
  41. /**
  42. * class 模版
  43. *
  44. * @time 2020年11月19日
  45. * @param Classes $class
  46. * @param \Closure $function
  47. * @return $this
  48. */
  49. public function class(Classes $class, \Closure $function)
  50. {
  51. $function($class);
  52. $this->astBuilder->addStmt($class->build());
  53. return $this;
  54. }
  55. /**
  56. * 条件
  57. *
  58. * @time 2020年11月19日
  59. * @param $condition
  60. * @param \Closure $closure
  61. * @return $this
  62. */
  63. public function when($condition, \Closure $closure)
  64. {
  65. if ($condition && $closure instanceof \Closure) {
  66. $closure($this);
  67. }
  68. return $this;
  69. }
  70. /**
  71. * 获取内容
  72. *
  73. * @time 2020年11月19日
  74. * @return string
  75. */
  76. public function getContent()
  77. {
  78. $stmts = array($this->astBuilder->getNode());
  79. $prettyPrinter = new Standard();
  80. return $prettyPrinter->prettyPrintFile($stmts);
  81. }
  82. /**
  83. * 输出
  84. *
  85. * @time 2020年11月19日
  86. * @return string
  87. */
  88. public function output()
  89. {
  90. return FileSystem::put($this->outPath . $this->filename, $this->getContent());
  91. }
  92. /**
  93. * 输出 Path
  94. *
  95. * @time 2020年11月19日
  96. * @param $path
  97. * @return $this
  98. */
  99. public function path($path)
  100. {
  101. CatchAdmin::makeDirectory($path);
  102. $this->outPath = $path;
  103. return $this;
  104. }
  105. /**
  106. * 设置文件名
  107. *
  108. * @time 2020年11月19日
  109. * @param $name
  110. * @return mixed
  111. */
  112. public function filename($name)
  113. {
  114. $this->filename = $name;
  115. return $this;
  116. }
  117. }