Router.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2013, Union of RAD (http://union-of-rad.org)
  6. * @license http://opensource.org/licenses/bsd-license.php The BSD License
  7. */
  8. namespace lithium\console;
  9. /**
  10. * The `Router` class uses an instance of `lithium\console\Request`, which represents an incoming
  11. * command-line invocation, to parse the correct command, and sub-command(s) and parameters, which
  12. * are used by `lithium\console\Dispatcher` to load and execute the proper `Command` class.
  13. */
  14. class Router extends \lithium\core\Object {
  15. /**
  16. * Parse incoming request from console. Short and long (GNU-style) options
  17. * in the form of `-f`, `--foo`, `--foo-bar` and `--foo=bar` are parsed.
  18. * XF68-style long options (i.e. `-foo`) are not supported but support
  19. * can be added by extending this class.
  20. *
  21. * @param object $request lithium\console\Request
  22. * @return array $params
  23. */
  24. public static function parse($request = null) {
  25. $defaults = array('command' => null, 'action' => 'run', 'args' => array());
  26. $params = $request ? (array) $request->params + $defaults : $defaults;
  27. if (!empty($request->argv)) {
  28. $args = $request->argv;
  29. while ($arg = array_shift($args)) {
  30. if (preg_match('/^-(?P<key>[a-zA-Z0-9])$/i', $arg, $match)) {
  31. $params[$match['key']] = true;
  32. continue;
  33. }
  34. if (preg_match('/^--(?P<key>[a-z0-9-]+)(?:=(?P<val>.+))?$/i', $arg, $match)) {
  35. $params[$match['key']] = !isset($match['val']) ? true : $match['val'];
  36. continue;
  37. }
  38. $params['args'][] = $arg;
  39. }
  40. }
  41. foreach (array('command', 'action') as $param) {
  42. if (!empty($params['args'])) {
  43. $params[$param] = array_shift($params['args']);
  44. }
  45. }
  46. return $params;
  47. }
  48. }
  49. ?>