Route.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. <?php
  2. namespace catcher\generate\factory;
  3. use catcher\facade\FileSystem;
  4. use catcher\generate\template\Content;
  5. class Route extends Factory
  6. {
  7. use Content;
  8. protected $controllerName;
  9. protected $controller;
  10. protected $restful;
  11. protected $methods = [];
  12. public function done($params = [])
  13. {
  14. $route = [];
  15. if ($this->restful) {
  16. $route[] = sprintf("\$router->resource('%s', '\%s');", $this->controllerName, $this->controller);
  17. }
  18. if (!empty($this->methods)) {
  19. foreach ($this->methods as $method) {
  20. $route[] = sprintf("\$router->%s('%s/%s', '\%s@%s');", $method[1], $this->controllerName, $method[0], $this->controller, $method[0] );
  21. }
  22. }
  23. $router = $this->getModulePath($this->controller) . DIRECTORY_SEPARATOR . 'route.php';
  24. $comment = '// ' . $this->controllerName . '路由';
  25. array_unshift($route, $comment);
  26. if (file_exists($router)) {
  27. return FileSystem::put($router, $this->parseRoute($router, $route));
  28. }
  29. return FileSystem::put($router, $this->header() . $comment. implode(';'. PHP_EOL , $route) . ';');
  30. }
  31. protected function parseRoute($path, $route)
  32. {
  33. $file = new \SplFileObject($path);
  34. // 保留所有行
  35. $lines = [];
  36. // 结尾之后的数据
  37. $down = [];
  38. // 结尾数据
  39. $end = '';
  40. while (!$file->eof()) {
  41. $lines[] = rtrim($file->current(), PHP_EOL);
  42. $file->next();
  43. }
  44. while (count($lines)) {
  45. $line = array_pop($lines);
  46. if (strpos($line, '})') !== false) {
  47. $end = $line;
  48. break;
  49. }
  50. array_unshift($down, $line);
  51. }
  52. $router = implode(PHP_EOL, $lines) . PHP_EOL;
  53. $routes = array_merge($down, $route);
  54. foreach ($routes as $r) {
  55. if ($r) {
  56. $router .= "\t" . $r . PHP_EOL;
  57. }
  58. }
  59. return $router .= $end;
  60. }
  61. /**
  62. * set class
  63. *
  64. * @time 2020年04月28日
  65. * @param $class
  66. * @return $this
  67. */
  68. public function controller($class)
  69. {
  70. $this->controller = $class;
  71. $class = explode('\\', $class);
  72. $this->controllerName = lcfirst(array_pop($class));
  73. return $this;
  74. }
  75. /**
  76. * set restful
  77. *
  78. * @time 2020年04月28日
  79. * @param $restful
  80. * @return $this
  81. */
  82. public function restful($restful)
  83. {
  84. $this->restful = $restful;
  85. return $this;
  86. }
  87. /**
  88. * set methods
  89. *
  90. * @time 2020年04月28日
  91. * @param $methods
  92. * @return $this
  93. */
  94. public function methods($methods)
  95. {
  96. $this->methods = $methods;
  97. return $this;
  98. }
  99. }