http-console.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * An example application using php-cli-tools and Buzz
  4. */
  5. require_once __DIR__ . '/vendor/autoload.php';
  6. define('BUZZ_PATH', realpath('../Buzz'));
  7. define('SCRIPT_NAME', array_shift($argv));
  8. require_once BUZZ_PATH . '/lib/Buzz/ClassLoader.php';
  9. Buzz\ClassLoader::register();
  10. class HttpConsole {
  11. protected $_host;
  12. protected $_prompt;
  13. public function __construct($host) {
  14. $this->_host = 'http://' . $host;
  15. $this->_prompt = '%K' . $this->_host . '%n/%K>%n ';
  16. }
  17. public function handleRequest($type, $path) {
  18. $request = new Buzz\Message\Request($type, $path, $this->_host);
  19. $response = new Buzz\Message\Response;
  20. $client = new Buzz\Client\FileGetContents();
  21. $client->send($request, $response);
  22. // Display headers
  23. foreach ($response->getHeaders() as $i => $header) {
  24. if ($i == 0) {
  25. \cli\line('%G{:header}%n', compact('header'));
  26. continue;
  27. }
  28. list($key, $value) = explode(': ', $header, 2);
  29. \cli\line('%W{:key}%n: {:value}', compact('key', 'value'));
  30. }
  31. \cli\line("\n");
  32. print $response->getContent() . "\n";
  33. switch ($type) {
  34. }
  35. }
  36. public function run() {
  37. while (true) {
  38. $cmd = \cli\prompt($this->_prompt, false, null);
  39. if (preg_match('/^(HEAD|GET|POST|PUT|DELETE) (\S+)$/', $cmd, $matches)) {
  40. $this->handleRequest($matches[1], $matches[2]);
  41. continue;
  42. }
  43. if ($cmd == '\q') {
  44. break;
  45. }
  46. }
  47. }
  48. }
  49. try {
  50. $console = new HttpConsole(array_shift($argv) ?: '127.0.0.1:80');
  51. $console->run();
  52. } catch (\Exception $e) {
  53. \cli\err("\n\n%R" . $e->getMessage() . "%n\n");
  54. }
  55. ?>