Request.php 1.57 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 11 12 13
 * @license http://www.yiiframework.com/license/
 */

namespace yii\console;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
14
class Request extends \yii\base\Request
Qiang Xue committed
15
{
Qiang Xue committed
16
	const ANONYMOUS_PARAMS = '-args';
Qiang Xue committed
17

Qiang Xue committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
	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 {
				$this->_params = array();
			}
		}
		return $this->_params;
	}

	/**
	 * Sets the command line arguments.
	 * @param array $params the command line arguments
	 */
	public function setParams($params)
Qiang Xue committed
42
	{
Qiang Xue committed
43
		$this->_params = $params;
Qiang Xue committed
44 45
	}

Qiang Xue committed
46 47 48 49
	/**
	 * 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
50
	public function resolve()
Qiang Xue committed
51
	{
Qiang Xue committed
52
		$rawParams = $this->getParams();
Qiang Xue committed
53
		if (isset($rawParams[0])) {
Qiang Xue committed
54
			$route = $rawParams[0];
Qiang Xue committed
55 56
			array_shift($rawParams);
		} else {
Qiang Xue committed
57
			$route = '';
Qiang Xue committed
58 59
		}

Qiang Xue committed
60
		$params = array(self::ANONYMOUS_PARAMS => array());
Qiang Xue committed
61 62 63
		foreach ($rawParams as $param) {
			if (preg_match('/^--(\w+)(=(.*))?$/', $param, $matches)) {
				$name = $matches[1];
Qiang Xue committed
64
				$params[$name] = isset($matches[3]) ? $matches[3] : true;
Qiang Xue committed
65
			} else {
Qiang Xue committed
66
				$params[self::ANONYMOUS_PARAMS][] = $param;
Qiang Xue committed
67 68
			}
		}
Qiang Xue committed
69 70

		return array($route, $params);
Qiang Xue committed
71 72
	}
}