You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.4 KiB

8 years ago
  1. <?php
  2. namespace FastRoute;
  3. if (!function_exists('FastRoute\simpleDispatcher')) {
  4. /**
  5. * @param callable $routeDefinitionCallback
  6. * @param array $options
  7. *
  8. * @return Dispatcher
  9. */
  10. function simpleDispatcher(callable $routeDefinitionCallback, array $options = []) {
  11. $options += [
  12. 'routeParser' => 'FastRoute\\RouteParser\\Std',
  13. 'dataGenerator' => 'FastRoute\\DataGenerator\\GroupCountBased',
  14. 'dispatcher' => 'FastRoute\\Dispatcher\\GroupCountBased',
  15. 'routeCollector' => 'FastRoute\\RouteCollector',
  16. ];
  17. /** @var RouteCollector $routeCollector */
  18. $routeCollector = new $options['routeCollector'](
  19. new $options['routeParser'], new $options['dataGenerator']
  20. );
  21. $routeDefinitionCallback($routeCollector);
  22. return new $options['dispatcher']($routeCollector->getData());
  23. }
  24. /**
  25. * @param callable $routeDefinitionCallback
  26. * @param array $options
  27. *
  28. * @return Dispatcher
  29. */
  30. function cachedDispatcher(callable $routeDefinitionCallback, array $options = []) {
  31. $options += [
  32. 'routeParser' => 'FastRoute\\RouteParser\\Std',
  33. 'dataGenerator' => 'FastRoute\\DataGenerator\\GroupCountBased',
  34. 'dispatcher' => 'FastRoute\\Dispatcher\\GroupCountBased',
  35. 'routeCollector' => 'FastRoute\\RouteCollector',
  36. 'cacheDisabled' => false,
  37. ];
  38. if (!isset($options['cacheFile'])) {
  39. throw new \LogicException('Must specify "cacheFile" option');
  40. }
  41. if (!$options['cacheDisabled'] && file_exists($options['cacheFile'])) {
  42. $dispatchData = require $options['cacheFile'];
  43. if (!is_array($dispatchData)) {
  44. throw new \RuntimeException('Invalid cache file "' . $options['cacheFile'] . '"');
  45. }
  46. return new $options['dispatcher']($dispatchData);
  47. }
  48. $routeCollector = new $options['routeCollector'](
  49. new $options['routeParser'], new $options['dataGenerator']
  50. );
  51. $routeDefinitionCallback($routeCollector);
  52. /** @var RouteCollector $routeCollector */
  53. $dispatchData = $routeCollector->getData();
  54. file_put_contents(
  55. $options['cacheFile'],
  56. '<?php return ' . var_export($dispatchData, true) . ';'
  57. );
  58. return new $options['dispatcher']($dispatchData);
  59. }
  60. }