|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- <?php
-
-
- namespace yii\console\controllers;
-
- use Yii;
- use yii\console\Controller;
- use yii\helpers\Console;
-
-
- class ServeController extends Controller
- {
- const EXIT_CODE_NO_DOCUMENT_ROOT = 2;
- const EXIT_CODE_NO_ROUTING_FILE = 3;
- const EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_SERVER = 4;
- const EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS = 5;
-
-
-
- public $port = 8080;
-
-
- public $docroot = '@app/web';
-
-
- public $router;
-
-
-
-
- public function actionIndex($address = 'localhost')
- {
- $documentRoot = Yii::getAlias($this->docroot);
-
- if (strpos($address, ':') === false) {
- $address = $address . ':' . $this->port;
- }
-
- if (!is_dir($documentRoot)) {
- $this->stdout("Document root \"$documentRoot\" does not exist.\n", Console::FG_RED);
- return self::EXIT_CODE_NO_DOCUMENT_ROOT;
- }
-
- if ($this->isAddressTaken($address)) {
- $this->stdout("http://$address is taken by another process.\n", Console::FG_RED);
- return self::EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS;
- }
-
- if ($this->router !== null && !file_exists($this->router)) {
- $this->stdout("Routing file \"$this->router\" does not exist.\n", Console::FG_RED);
- return self::EXIT_CODE_NO_ROUTING_FILE;
- }
-
- $this->stdout("Server started on http://{$address}/\n");
- $this->stdout("Document root is \"{$documentRoot}\"\n");
- if ($this->router) {
- $this->stdout("Routing file is \"$this->router\"\n");
- }
- $this->stdout("Quit the server with CTRL-C or COMMAND-C.\n");
-
- passthru('"' . PHP_BINARY . '"' . " -S {$address} -t \"{$documentRoot}\" $this->router");
- }
-
-
-
- public function options($actionID)
- {
- return array_merge(parent::options($actionID), [
- 'docroot',
- 'router',
- 'port',
- ]);
- }
-
-
-
- public function optionAliases()
- {
- return array_merge(parent::optionAliases(), [
- 't' => 'docroot',
- 'p' => 'port',
- 'r' => 'router',
- ]);
- }
-
-
-
- protected function isAddressTaken($address)
- {
- list($hostname, $port) = explode(':', $address);
- $fp = @fsockopen($hostname, $port, $errno, $errstr, 3);
- if ($fp === false) {
- return false;
- }
- fclose($fp);
- return true;
- }
- }
|