Skip to content

Commit

Permalink
Move Swoole-nyholm to a new package
Browse files Browse the repository at this point in the history
  • Loading branch information
Nyholm committed Jul 17, 2021
0 parents commit 46fd48f
Show file tree
Hide file tree
Showing 18 changed files with 625 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# These are supported funding model platforms

github: [nyholm]
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/composer.lock
/phpunit.xml
/vendor/
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Change Log

## 0.1.0

First version
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2021 Tobias Nyholm

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
95 changes: 95 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Swoole Runtime with nyholm/psr7

A runtime for [Swoole](https://www.swoole.co.uk/).

If you are new to the Symfony Runtime component, read more in the [main readme](https://github.com/php-runtime/runtime).

## Installation

```
composer require runtime/swoole-nyholm
```

## Usage

Define the environment variable `APP_RUNTIME` for your application.

```
APP_RUNTIME=Runtime\SwooleNyholm\Runtime
```

### Pure PHP

```php
// public/index.php

use Swoole\Http\Request;
use Swoole\Http\Response;

require_once dirname(__DIR__).'/vendor/autoload_runtime.php';

return function () {
return function (Request $request, Response $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello World\n");
};
};
```

### PSR

```php
// public/index.php

use Nyholm\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

require_once dirname(__DIR__).'/vendor/autoload_runtime.php';

class App implements RequestHandlerInterface {
public function handle(ServerRequestInterface $request): ResponseInterface {
$name = $request->getQueryParams()['name'] ?? 'World';
return new Response(200, ['Server' => 'swoole-runtime'], "Hello, $name!");
}
}

return function(): RequestHandlerInterface {
return new App();
};
```

## Using Options

You can define some configurations using Symfony's Runtime `APP_RUNTIME_OPTIONS` API.

| Option | Description | Default |
| --- | --- | --- |
| `host` | The host where the server should binds to (precedes `SWOOLE_HOST` environment variable) | `127.0.0.1` |
| `port` | The port where the server should be listing (precedes `SWOOLE_PORT` environment variable) | `8000` |
| `mode` | Swoole's server mode (precedes `SWOOLE_MODE` environment variable) | `SWOOLE_PROCESS` |
| `settings` | All Swoole's server settings ([swoole.co.uk/docs/modules/swoole-server/configuration](https://www.swoole.co.uk/docs/modules/swoole-server/configuration)) | `[]` |

```php
// public/index.php

use App\Kernel;

$_SERVER['APP_RUNTIME_OPTIONS'] = [
'host' => '0.0.0.0',
'port' => 9501,
'mode' => SWOOLE_BASE,
'settings' => [
\Swoole\Constant::OPTION_WORKER_NUM => swoole_cpu_num() * 2,
\Swoole\Constant::OPTION_ENABLE_STATIC_HANDLER => true,
\Swoole\Constant::OPTION_DOCUMENT_ROOT => dirname(__DIR__).'/public'
],
];

require_once dirname(__DIR__).'/vendor/autoload_runtime.php';

return function (array $context) {
return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};
```
32 changes: 32 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "runtime/swoole-nyholm",
"type": "library",
"description": "Swoole runtime with nyholm/psr7",
"license": "MIT",
"authors": [
{
"name": "Tobias Nyholm",
"email": "[email protected]"
}
],
"require": {
"nyholm/psr7": "^1.4",
"psr/http-server-handler": "^1.0",
"symfony/runtime": "^5.3 || ^6.0"
},
"require-dev": {
"symfony/phpunit-bridge": "^5.3"
},
"autoload": {
"psr-4": {
"Runtime\\SwooleNyholm\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Runtime\\SwooleNyholm\\Tests\\": "tests/"
}
},
"minimum-stability": "dev",
"prefer-stable": true
}
23 changes: 23 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php"
failOnRisky="true"
failOnWarning="true"
>
<php>
<ini name="error_reporting" value="-1"/>
</php>
<testsuites>
<testsuite name="Unit">
<directory>./tests/Unit</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>
31 changes: 31 additions & 0 deletions src/CallableRunner.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Runtime\SwooleNyholm;

use Symfony\Component\Runtime\RunnerInterface;

/**
* A simple runner that will run a callable.
*
* @author Tobias Nyholm <[email protected]>
*/
class CallableRunner implements RunnerInterface
{
/** @var ServerFactory */
private $serverFactory;
/** @var callable */
private $application;

public function __construct(ServerFactory $serverFactory, callable $application)
{
$this->serverFactory = $serverFactory;
$this->application = $application;
}

public function run(): int
{
$this->serverFactory->createServer($this->application)->start();

return 0;
}
}
80 changes: 80 additions & 0 deletions src/RequestHandlerRunner.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

namespace Runtime\SwooleNyholm;

use Psr\Http\Server\RequestHandlerInterface;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Symfony\Component\Runtime\RunnerInterface;

class RequestHandlerRunner implements RunnerInterface
{
private const CHUNK_SIZE = 2097152; // 2MB

/**
* @var ServerFactory
*/
private $serverFactory;

/**
* @var RequestHandlerInterface
*/
private $application;

public function __construct(ServerFactory $serverFactory, RequestHandlerInterface $application)
{
$this->serverFactory = $serverFactory;
$this->application = $application;
}

public function run(): int
{
$this->serverFactory->createServer([$this, 'handle'])->start();

return 0;
}

public function handle(Request $request, Response $response): void
{
$psrRequest = (new \Nyholm\Psr7\ServerRequest(
$request->getMethod(),
$request->server['request_uri'] ?? '/',
array_change_key_case($request->server ?? [], CASE_UPPER),
$request->rawContent(),
'1.1',
$request->server ?? []
))
->withQueryParams($request->get ?? []);

$psrResponse = $this->application->handle($psrRequest);

$response->setStatusCode($psrResponse->getStatusCode(), $psrResponse->getReasonPhrase());

foreach ($psrResponse->getHeaders() as $name => $values) {
foreach ($values as $value) {
$response->setHeader($name, $value);
}
}

$body = $psrResponse->getBody();
$body->rewind();

if ($body->isReadable()) {
if ($body->getSize() <= self::CHUNK_SIZE) {
if ($contents = $body->getContents()) {
$response->write($contents);
}
} else {
while (!$body->eof() && ($contents = $body->read(self::CHUNK_SIZE))) {
$response->write($contents);
}
}

$response->end();
} else {
$response->end((string) $body);
}

$body->close();
}
}
37 changes: 37 additions & 0 deletions src/Runtime.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

namespace Runtime\SwooleNyholm;

use Psr\Http\Server\RequestHandlerInterface;
use Symfony\Component\Runtime\RunnerInterface;
use Symfony\Component\Runtime\SymfonyRuntime;

/**
* A runtime for Swoole.
*
* @author Tobias Nyholm <[email protected]>
*/
class Runtime extends SymfonyRuntime
{
/** @var ?ServerFactory */
private $serverFactory;

public function __construct(array $options, ?ServerFactory $serverFactory = null)
{
$this->serverFactory = $serverFactory ?? new ServerFactory($options);
parent::__construct($this->serverFactory->getOptions());
}

public function getRunner(?object $application): RunnerInterface
{
if (is_callable($application)) {

This comment has been minimized.

Copy link
@rvanlaak

rvanlaak Jul 19, 2021

Would these checks not be a responsibility of the runner itself? What if there will be several other runners added?

return new CallableRunner($this->serverFactory, $application);
}

if ($application instanceof RequestHandlerInterface) {
return new RequestHandlerRunner($this->serverFactory, $application);
}

return parent::getRunner($application);
}
}
51 changes: 51 additions & 0 deletions src/ServerFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace Runtime\SwooleNyholm;

use Swoole\Http\Server;

/**
* A factory for Swoole HTTP Servers.
*
* @author Tobias Nyholm <[email protected]>
*/
class ServerFactory
{
private const DEFAULT_OPTIONS = [
'host' => '127.0.0.1',
'port' => 8000,
'mode' => 2, // SWOOLE_PROCESS
'settings' => [],
];

/** @var array */
private $options;

public static function getDefaultOptions(): array
{
return self::DEFAULT_OPTIONS;
}

public function __construct(array $options = [])
{
$options['host'] = $options['host'] ?? $_SERVER['SWOOLE_HOST'] ?? $_ENV['SWOOLE_HOST'] ?? self::DEFAULT_OPTIONS['host'];
$options['port'] = $options['port'] ?? $_SERVER['SWOOLE_PORT'] ?? $_ENV['SWOOLE_PORT'] ?? self::DEFAULT_OPTIONS['port'];
$options['mode'] = $options['mode'] ?? $_SERVER['SWOOLE_MODE'] ?? $_ENV['SWOOLE_MODE'] ?? self::DEFAULT_OPTIONS['mode'];

$this->options = array_replace_recursive(self::DEFAULT_OPTIONS, $options);
}

public function createServer(callable $requestHandler): Server
{
$server = new Server($this->options['host'], (int) $this->options['port'], (int) $this->options['mode']);
$server->set($this->options['settings']);
$server->on('request', $requestHandler);

return $server;
}

public function getOptions(): array
{
return $this->options;
}
}
Loading

0 comments on commit 46fd48f

Please sign in to comment.