1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (https://nette.org)
5: * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6: */
7:
8: namespace Nette\Application\Routers;
9:
10: use Nette;
11: use Nette\Application;
12:
13:
14: /**
15: * The unidirectional router for CLI. (experimental)
16: */
17: class CliRouter implements Application\IRouter
18: {
19: use Nette\SmartObject;
20:
21: const PRESENTER_KEY = 'action';
22:
23: /** @var array */
24: private $defaults;
25:
26:
27: /**
28: * @param array default values
29: */
30: public function __construct($defaults = [])
31: {
32: $this->defaults = $defaults;
33: }
34:
35:
36: /**
37: * Maps command line arguments to a Request object.
38: * @return Nette\Application\Request|null
39: */
40: public function match(Nette\Http\IRequest $httpRequest)
41: {
42: if (empty($_SERVER['argv']) || !is_array($_SERVER['argv'])) {
43: return null;
44: }
45:
46: $names = [self::PRESENTER_KEY];
47: $params = $this->defaults;
48: $args = $_SERVER['argv'];
49: array_shift($args);
50: $args[] = '--';
51:
52: foreach ($args as $arg) {
53: $opt = preg_replace('#/|-+#A', '', $arg);
54: if ($opt === $arg) {
55: if (isset($flag) || $flag = array_shift($names)) {
56: $params[$flag] = $arg;
57: } else {
58: $params[] = $arg;
59: }
60: $flag = null;
61: continue;
62: }
63:
64: if (isset($flag)) {
65: $params[$flag] = true;
66: $flag = null;
67: }
68:
69: if ($opt !== '') {
70: $pair = explode('=', $opt, 2);
71: if (isset($pair[1])) {
72: $params[$pair[0]] = $pair[1];
73: } else {
74: $flag = $pair[0];
75: }
76: }
77: }
78:
79: if (!isset($params[self::PRESENTER_KEY])) {
80: throw new Nette\InvalidStateException('Missing presenter & action in route definition.');
81: }
82: list($module, $presenter) = Nette\Application\Helpers::splitName($params[self::PRESENTER_KEY]);
83: if ($module !== '') {
84: $params[self::PRESENTER_KEY] = $presenter;
85: $presenter = $module;
86: }
87:
88: return new Application\Request(
89: $presenter,
90: 'CLI',
91: $params
92: );
93: }
94:
95:
96: /**
97: * This router is only unidirectional.
98: * @return void
99: */
100: public function constructUrl(Application\Request $appRequest, Nette\Http\Url $refUrl)
101: {
102: }
103:
104:
105: /**
106: * Returns default values.
107: * @return array
108: */
109: public function getDefaults()
110: {
111: return $this->defaults;
112: }
113: }
114: