Route.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\console\command\optimize;
  12. use think\console\Command;
  13. use think\console\Input;
  14. use think\console\Output;
  15. class Route extends Command
  16. {
  17. /** @var Output */
  18. protected $output;
  19. protected function configure()
  20. {
  21. $this->setName('optimize:route')
  22. ->setDescription('Build route cache.');
  23. }
  24. protected function execute(Input $input, Output $output)
  25. {
  26. file_put_contents(RUNTIME_PATH . 'route.php', $this->buildRouteCache());
  27. $output->writeln('<info>Succeed!</info>');
  28. }
  29. protected function buildRouteCache()
  30. {
  31. $files = \think\Config::get('route_config_file');
  32. foreach ($files as $file) {
  33. if (is_file(CONF_PATH . $file . CONF_EXT)) {
  34. $config = include CONF_PATH . $file . CONF_EXT;
  35. if (is_array($config)) {
  36. \think\Route::import($config);
  37. }
  38. }
  39. }
  40. $rules = \think\Route::rules(true);
  41. array_walk_recursive($rules, [$this, 'buildClosure']);
  42. $content = '<?php ' . PHP_EOL . 'return ';
  43. $content .= var_export($rules, true) . ';';
  44. $content = str_replace(['\'[__start__', '__end__]\''], '', stripcslashes($content));
  45. return $content;
  46. }
  47. protected function buildClosure(&$value)
  48. {
  49. if ($value instanceof \Closure) {
  50. $reflection = new \ReflectionFunction($value);
  51. $startLine = $reflection->getStartLine();
  52. $endLine = $reflection->getEndLine();
  53. $file = $reflection->getFileName();
  54. $item = file($file);
  55. $content = '';
  56. for ($i = $startLine - 1; $i <= $endLine - 1; $i++) {
  57. $content .= $item[$i];
  58. }
  59. $start = strpos($content, 'function');
  60. $end = strrpos($content, '}');
  61. $value = '[__start__' . substr($content, $start, $end - $start + 1) . '__end__]';
  62. }
  63. }
  64. }