serve.php (2549B)
1 <?php 2 // Serve extension, https://github.com/annaesvensson/yellow-serve 3 4 class YellowServe { 5 const VERSION = "0.9.1"; 6 public $yellow; // access to API 7 8 // Handle initialisation 9 public function onLoad($yellow) { 10 $this->yellow = $yellow; 11 } 12 13 // Handle command 14 public function onCommand($command, $text) { 15 switch ($command) { 16 case "serve": $statusCode = $this->processCommandServe($command, $text); break; 17 default: $statusCode = 0; 18 } 19 return $statusCode; 20 } 21 22 // Handle command help 23 public function onCommandHelp() { 24 return "serve [url]"; 25 } 26 27 // Process command to start web server 28 public function processCommandServe($command, $text) { 29 list($url) = $this->yellow->toolbox->getTextArguments($text); 30 if (is_string_empty($url)) $url = "http://localhost:8000/"; 31 list($scheme, $address, $base) = $this->yellow->lookup->getUrlInformation($url); 32 if ($scheme=="http" && !is_string_empty($address) && is_string_empty($base)) { 33 if (!preg_match("/\:\d+$/", $address)) $address .= ":8000"; 34 if ($this->checkServerSettings("$scheme://$address/")) { 35 echo "Starting web server. Open a web browser and go to $scheme://$address/\n"; 36 echo "Press Ctrl+C to quit...\n"; 37 exec(PHP_BINARY." -S $address yellow.php 2>&1", $outputLines, $returnStatus); 38 $statusCode = $returnStatus!=0 ? 500 : 200; 39 if ($statusCode!=200) { 40 $output = !is_array_empty($outputLines) ? end($outputLines) : "Please check arguments!"; 41 if (preg_match("/^\[(.*?)\]\s*(.*)$/", $output, $matches)) $output = $matches[2]; 42 echo "ERROR starting web server: $output\n"; 43 } 44 } else { 45 $statusCode = 400; 46 $fileName = $this->yellow->system->get("coreExtensionDirectory").$this->yellow->system->get("coreSystemFile"); 47 echo "ERROR starting web server: Please configure `CoreServerUrl: auto` in file '$fileName'!\n"; 48 } 49 } else { 50 $statusCode = 400; 51 echo "Yellow $command: Invalid arguments\n"; 52 } 53 return $statusCode; 54 } 55 56 // Check server settings 57 public function checkServerSettings($url) { 58 return $this->yellow->system->get("coreServerUrl")=="auto" || 59 $this->yellow->system->get("coreServerUrl")==$url; 60 } 61 }