Example #1
0
 public function handle(Request $request, array $args) : \Generator
 {
     $html = $this->app->getRenderer()->render('sitemap.xml', ['lastmod' => date('c', filemtime(__DIR__ . '/../../templates/index.mustache')), 'articles' => $this->app->getArticleStore()->getIterator()]);
     $sink = new MemorySink();
     yield from $sink->end($html);
     return new BasicResponse(200, ['Content-Type' => 'application/xml', 'Content-Length' => $sink->getLength()], $sink);
 }
Example #2
0
 public function handle(Request $request, array $args) : \Generator
 {
     $html = $this->app->getRenderer()->render('blog', ['articles' => $this->app->getArticleStore()->getIterator()]);
     $sink = new MemorySink();
     yield from $sink->end($html);
     return new BasicResponse(200, ['Content-Type' => 'text/html', 'Content-Length' => $sink->getLength()], $sink);
 }
Example #3
0
 /**
  * Handles an incoming HTTP request and dispatches it to the appropriate action.
  *
  * @param  Request $request The HTTP request message.
  * @param  Socket  $socket  The client socket connection.
  *
  * @return \Generator
  *
  * @resolve \Icicle\Http\Message\Response The appropriate HTTP response.
  */
 public function onRequest(Request $request, Socket $socket) : \Generator
 {
     $dispatched = $this->app->getDispatcher()->dispatch($request->getMethod(), $request->getUri()->getPath());
     switch ($dispatched[0]) {
         case FastRoute\Dispatcher::NOT_FOUND:
             // no route found
             $randomStr = '';
             for ($i = 0; $i < 1000; ++$i) {
                 $char = chr(mt_rand(32, 126));
                 if ($char !== '<') {
                     $randomStr .= $char;
                 }
             }
             $html = $this->app->getRenderer()->render('404', ['randomStr' => $randomStr]);
             $sink = new MemorySink();
             yield from $sink->end($html);
             return new BasicResponse(404, ['Content-Type' => 'text/html', 'Content-Length' => $sink->getLength()], $sink);
         case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
             // HTTP request method not allowed
             $sink = new MemorySink();
             yield from $sink->end('405 Method Not Allowed');
             return new BasicResponse(405, ['Content-Type' => 'text/plain', 'Content-Length' => $sink->getLength()], $sink);
         case FastRoute\Dispatcher::FOUND:
             // route was found
             $action = new $dispatched[1]($this->app);
             $response = (yield from $action->handle($request, $dispatched[2]));
             return $response;
         default:
             throw new \RuntimeException('Invalid router state');
     }
 }
Example #4
0
 /**
  * {@inheritdoc}
  */
 public function createResponse(Application $application, Request $request, Socket $socket) : Response
 {
     if (!$request->hasHeader('Sec-WebSocket-Key')) {
         $sink = new MemorySink('No WebSocket key header provided.');
         return new BasicResponse(Response::BAD_REQUEST, ['Connection' => 'close', 'Content-Length' => $sink->getLength()], $sink);
     }
     $headers = ['Connection' => 'upgrade', 'Upgrade' => 'websocket', 'Sec-WebSocket-Accept' => $this->responseKey(trim($request->getHeader('Sec-WebSocket-Key')))];
     if ($application instanceof SubProtocol) {
         $protocol = $application->selectSubProtocol(array_map('trim', explode(',', $request->getHeader('Sec-WebSocket-Protocol'))));
         if (strlen($protocol)) {
             $headers['Sec-WebSocket-Protocol'] = $protocol;
         }
     }
     /*
     $extensions = $application->selectExtensions(
         array_map('trim', explode(',', $request->getHeader('Sec-WebSocket-Extensions')))
     );
     
     if (!empty($extensions)) {
         $headers['Sec-WebSocket-Extensions'] = $extensions;
     }
     */
     $response = new BasicResponse(Response::SWITCHING_PROTOCOLS, $headers);
     $connection = $this->createConnection($response, $socket, false);
     return new WebSocketResponse($application, $connection, $response);
 }
Example #5
0
 public function handle(Request $request, array $args) : \Generator
 {
     $article = $this->app->getArticleStore()->getBySlug(substr($request->getUri()->getPath(), 1));
     $html = $this->app->getRenderer()->render('article', ['article' => $article]);
     $sink = new MemorySink();
     yield from $sink->end($html);
     return new BasicResponse(200, ['Content-Type' => 'text/html', 'Content-Length' => $sink->getLength()], $sink);
 }
Example #6
0
 public function handle(Request $request, array $args) : \Generator
 {
     $manager = $this->app->getAssetManager();
     $sink = new MemorySink();
     if (!$manager->exists($args['asset'])) {
         yield from $sink->end('404 Resource Not Found');
         return new BasicResponse(404, ['Content-Type' => 'text/plain', 'Content-Length' => $sink->getLength()], $sink);
     }
     yield from $sink->end($manager->getBytes($args['asset']));
     return new BasicResponse(200, ['Content-Type' => $manager->getMimeType($args['asset']), 'Content-Length' => $sink->getLength()], $sink);
 }
Example #7
0
 public function handle(Request $request, array $args) : \Generator
 {
     if (isset($args['category'])) {
         $articles = $this->app->getArticleStore()->getByCategory($args['category']);
     } else {
         $articles = $this->app->getArticleStore()->getIterator();
     }
     $html = $this->app->getRenderer()->render('feed.atom', ['updated' => Carbon::now(), 'articles' => $articles]);
     $sink = new MemorySink();
     yield from $sink->end($html);
     return new BasicResponse(200, ['Content-Type' => 'application/xml', 'Content-Length' => $sink->getLength()], $sink);
 }
 /**
  * {@inheritdoc}
  */
 public function createResponse(Application $application, Request $request, Socket $socket) : Response
 {
     if ($request->getMethod() !== 'GET') {
         $sink = new MemorySink('Only GET requests allowed for WebSocket connections.');
         return new BasicResponse(Response::METHOD_NOT_ALLOWED, ['Connection' => 'close', 'Upgrade' => 'websocket', 'Content-Length' => $sink->getLength(), 'Content-Type' => 'text/plain'], $sink);
     }
     if (!in_array('upgrade', array_map('trim', explode(',', strtolower($request->getHeader('Connection')))), true) || strtolower($request->getHeader('Upgrade')) !== 'websocket') {
         $sink = new MemorySink('Must upgrade to WebSocket connection for requested resource.');
         return new BasicResponse(Response::UPGRADE_REQUIRED, ['Connection' => 'close', 'Upgrade' => 'websocket', 'Content-Length' => $sink->getLength(), 'Content-Type' => 'text/plain'], $sink);
     }
     if (!$this->protocol->isProtocol($request)) {
         $sink = new MemorySink('Unsupported protocol version.');
         return new BasicResponse(Response::UPGRADE_REQUIRED, ['Connection' => 'close', 'Content-Length' => $sink->getLength(), 'Content-Type' => 'text/plain', 'Upgrade' => 'websocket', 'Sec-WebSocket-Version' => $this->getSupportedVersions()], $sink);
     }
     return $this->protocol->createResponse($application, $request, $socket);
 }
<?php

require __DIR__ . "/../vendor/autoload.php";
use AsyncPHP\Icicle\Database\ManagerFactory;
use Icicle\Http\Message\RequestInterface;
use Icicle\Http\Message\Response;
use Icicle\Http\Server\Server;
use Icicle\Loop;
use Icicle\Socket\SocketInterface;
use Icicle\Stream\MemorySink;
$factory = new ManagerFactory();
$manager = $factory->create(require __DIR__ . "/config.php");
$server = new Server(function (RequestInterface $request, SocketInterface $socket) use($manager) {
    try {
        (yield $manager->table("test")->delete());
        for ($i = 0; $i < 5; $i++) {
            (yield $manager->table("test")->insert(["text" => "foo"]));
        }
        $result = (yield $manager->table("test")->select()->get());
    } catch (Exception $e) {
        die($e->getMessage());
    }
    $sink = new MemorySink();
    (yield $sink->end(count($result)));
    $response = new Response(200, ["Content-type" => "text/plain", "Content-length" => $sink->getLength()], $sink);
    (yield $response);
});
$server->listen(8000);
Loop\run();
Example #10
0
<?php

use Icicle\Http\Client\Client;
use Icicle\Http\Message\RequestInterface;
use Icicle\Http\Message\Response;
use Icicle\Http\Message\ResponseInterface;
use Icicle\Socket\SocketInterface;
use Icicle\Stream\MemorySink;
$collector->addRoute("GET", "/", function (RequestInterface $request, SocketInterface $socket) {
    $stream = new MemorySink();
    (yield $stream->end("hello world"));
    (yield new Response(200, ["content-type" => "text/html", "content-length" => $stream->getLength()], $stream));
});
$collector->addRoute("GET", "/test", function (RequestInterface $request, SocketInterface $socket) {
    $client = new Client();
    /** @var ResponseInterface $response */
    $response = (yield $client->request("GET", "http://jsonplaceholder.typicode.com/posts/1"));
    $stream1 = $response->getBody();
    $stream2 = new MemorySink();
    while ($stream1->isReadable()) {
        $data = (yield $stream1->read());
        (yield $stream2->write($data));
    }
    (yield $stream2->end());
    (yield new Response(200, ["content-type" => "text/html", "content-length" => $stream2->getLength()], $stream2));
});
Example #11
0
 public function onHttp(Request $request, Socket $socket) : Generator
 {
     $stream = new MemorySink();
     yield from $stream->end("\n            <script>\n                var socket = new WebSocket('ws://127.0.0.1:8888/socket');\n\n                socket.addEventListener('open', function() {\n                    console.log(arguments);\n                });\n\n                socket.addEventListener('message', function() {\n                    console.log(arguments);\n                });\n\n                socket.addEventListener('error', function() {\n                    console.log(arguments);\n                });\n\n                socket.addEventListener('close', function() {\n                    console.log(arguments);\n                });\n            </script>\n        ");
     (yield new BasicResponse(200, ["Content-Type" => "text/html", "Content-Length" => $stream->getLength()], $stream));
 }
Example #12
0
use Icicle\Socket\SocketInterface;
use Icicle\Stream\MemorySink;
$cache = new MemoryDriver();
$server = new Server(function (RequestInterface $request, SocketInterface $socket) use($cache) {
    try {
        $cached = (yield $cache->get("foo"));
        if (!$cached) {
            $cached = (yield $cache->set("foo", function () {
                $client = new Client();
                /** @var ResponseInterface $response */
                $response = (yield $client->request("GET", "https://icicle.io/"));
                $data = "";
                $stream = $response->getBody();
                while ($stream->isReadable()) {
                    $data .= (yield $stream->read());
                }
                (yield $data);
            }));
        }
        $stream = new MemorySink();
        (yield $stream->end($cached));
        $response = new Response(200, ["content-type" => "text/html", "content-length" => $stream->getLength()], $stream);
        (yield $response);
        $stream = null;
        $response = null;
    } catch (Exception $e) {
        print $e->getMessage();
    }
});
$server->listen(8000);
Loop\run();
Example #13
0
 /**
  * @coroutine
  *
  * @param int $code
  *
  * @return \Generator
  *
  * @resolve \Icicle\Http\Message\Response
  */
 protected function createDefaultErrorResponse(int $code) : \Generator
 {
     $sink = new MemorySink(sprintf('%d Error', $code));
     $headers = ['Connection' => 'close', 'Content-Type' => 'text/plain', 'Content-Length' => $sink->getLength()];
     return new BasicResponse($code, $headers, $sink);
     yield;
     // Unreachable, but makes method a coroutine.
 }