Route.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. if (!is_dir(RUNTIME_PATH)) {
  27. @mkdir(RUNTIME_PATH, 0755, true);
  28. }
  29. file_put_contents(RUNTIME_PATH . 'route.php', $this->buildRouteCache());
  30. $output->writeln('<info>Succeed!</info>');
  31. }
  32. protected function buildRouteCache()
  33. {
  34. $files = \think\Config::get('route_config_file');
  35. foreach ($files as $file) {
  36. if (is_file(CONF_PATH . $file . CONF_EXT)) {
  37. $config = include CONF_PATH . $file . CONF_EXT;
  38. if (is_array($config)) {
  39. \think\Route::import($config);
  40. }
  41. }
  42. }
  43. $rules = \think\Route::rules(true);
  44. array_walk_recursive($rules, [$this, 'buildClosure']);
  45. $content = '<?php ' . PHP_EOL . 'return ';
  46. $content .= var_export($rules, true) . ';';
  47. $content = str_replace(['\'[__start__', '__end__]\''], '', stripcslashes($content));
  48. return $content;
  49. }
  50. protected function buildClosure(&$value)
  51. {
  52. if ($value instanceof \Closure) {
  53. $reflection = new \ReflectionFunction($value);
  54. $startLine = $reflection->getStartLine();
  55. $endLine = $reflection->getEndLine();
  56. $file = $reflection->getFileName();
  57. $item = file($file);
  58. $content = '';
  59. for ($i = $startLine - 1; $i <= $endLine - 1; $i++) {
  60. $content .= $item[$i];
  61. }
  62. $start = strpos($content, 'function');
  63. $end = strrpos($content, '}');
  64. $value = '[__start__' . substr($content, $start, $end - $start + 1) . '__end__]';
  65. }
  66. }
  67. }