Request.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\console;
  8. /**
  9. * The console Request represents the environment information for a console application.
  10. *
  11. * It is a wrapper for the PHP `$_SERVER` variable which holds information about the
  12. * currently running PHP script and the command line arguments given to it.
  13. *
  14. * @property array $params The command line arguments. It does not include the entry script name.
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @since 2.0
  18. */
  19. class Request extends \yii\base\Request
  20. {
  21. private $_params;
  22. /**
  23. * Returns the command line arguments.
  24. * @return array the command line arguments. It does not include the entry script name.
  25. */
  26. public function getParams()
  27. {
  28. if ($this->_params === null) {
  29. if (isset($_SERVER['argv'])) {
  30. $this->_params = $_SERVER['argv'];
  31. array_shift($this->_params);
  32. } else {
  33. $this->_params = [];
  34. }
  35. }
  36. return $this->_params;
  37. }
  38. /**
  39. * Sets the command line arguments.
  40. * @param array $params the command line arguments
  41. */
  42. public function setParams($params)
  43. {
  44. $this->_params = $params;
  45. }
  46. /**
  47. * Resolves the current request into a route and the associated parameters.
  48. * @return array the first element is the route, and the second is the associated parameters.
  49. */
  50. public function resolve()
  51. {
  52. $rawParams = $this->getParams();
  53. $endOfOptionsFound = false;
  54. if (isset($rawParams[0])) {
  55. $route = array_shift($rawParams);
  56. if ($route === '--') {
  57. $endOfOptionsFound = true;
  58. $route = array_shift($rawParams);
  59. }
  60. } else {
  61. $route = '';
  62. }
  63. $params = [];
  64. foreach ($rawParams as $param) {
  65. if ($endOfOptionsFound) {
  66. $params[] = $param;
  67. } elseif ($param === '--') {
  68. $endOfOptionsFound = true;
  69. } elseif (preg_match('/^--(\w+)(?:=(.*))?$/', $param, $matches)) {
  70. $name = $matches[1];
  71. if ($name !== Application::OPTION_APPCONFIG) {
  72. $params[$name] = isset($matches[2]) ? $matches[2] : true;
  73. }
  74. } elseif (preg_match('/^-(\w+)(?:=(.*))?$/', $param, $matches)) {
  75. $name = $matches[1];
  76. if (is_numeric($name)) {
  77. $params[] = $param;
  78. } else {
  79. $params['_aliases'][$name] = isset($matches[2]) ? $matches[2] : true;
  80. }
  81. } else {
  82. $params[] = $param;
  83. }
  84. }
  85. return [$route, $params];
  86. }
  87. }