Request.php 1.81 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7 8 9 10
 * @license http://www.yiiframework.com/license/
 */

namespace yii\console;

/**
11 12 13 14
 * The console Request represents the environment information for a console application.
 *
 * It is a wrapper for the PHP `$_SERVER` variable which holds information about the
 * currently running PHP script and the command line arguments given to it.
15 16 17
 *
 * @property array $params The command line arguments. It does not include the entry script name.
 *
Qiang Xue committed
18 19 20
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
21
class Request extends \yii\base\Request
Qiang Xue committed
22
{
Qiang Xue committed
23 24 25 26 27 28 29 30 31 32 33 34 35
	private $_params;

	/**
	 * Returns the command line arguments.
	 * @return array the command line arguments. It does not include the entry script name.
	 */
	public function getParams()
	{
		if (!isset($this->_params)) {
			if (isset($_SERVER['argv'])) {
				$this->_params = $_SERVER['argv'];
				array_shift($this->_params);
			} else {
Alexander Makarov committed
36
				$this->_params = [];
Qiang Xue committed
37 38 39 40 41 42 43 44 45 46
			}
		}
		return $this->_params;
	}

	/**
	 * Sets the command line arguments.
	 * @param array $params the command line arguments
	 */
	public function setParams($params)
Qiang Xue committed
47
	{
Qiang Xue committed
48
		$this->_params = $params;
Qiang Xue committed
49 50
	}

Qiang Xue committed
51 52 53 54
	/**
	 * Resolves the current request into a route and the associated parameters.
	 * @return array the first element is the route, and the second is the associated parameters.
	 */
Qiang Xue committed
55
	public function resolve()
Qiang Xue committed
56
	{
Qiang Xue committed
57
		$rawParams = $this->getParams();
Qiang Xue committed
58
		if (isset($rawParams[0])) {
Qiang Xue committed
59
			$route = $rawParams[0];
Qiang Xue committed
60 61
			array_shift($rawParams);
		} else {
Qiang Xue committed
62
			$route = '';
Qiang Xue committed
63 64
		}

Alexander Makarov committed
65
		$params = [];
Qiang Xue committed
66 67 68
		foreach ($rawParams as $param) {
			if (preg_match('/^--(\w+)(=(.*))?$/', $param, $matches)) {
				$name = $matches[1];
Qiang Xue committed
69
				$params[$name] = isset($matches[3]) ? $matches[3] : true;
Qiang Xue committed
70
			} else {
Qiang Xue committed
71
				$params[] = $param;
Qiang Xue committed
72 73
			}
		}
Qiang Xue committed
74

Alexander Makarov committed
75
		return [$route, $params];
Qiang Xue committed
76 77
	}
}