Skip to content

feat: add a runtime for FrankenPHP with Symfony #124

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,12 @@ Build high-performance, scalable, concurrent HTTP services with [Swoole](https:/
* https://github.com/php-runtime/swoole
* https://github.com/php-runtime/swoole-nyholm

### FrankenPHP

Run your Symfony application with the [FrankenPHP](https://frankenphp.dev) app server.

* https://github.com/php-runtime/frankenphp-symfony

### PHP-FPM and traditional web servers

These runtimes are for PHP-FPM and the more traditional web servers one might
Expand Down
5 changes: 5 additions & 0 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,8 @@ parameters:
message: "#CurlHandle#"
count: 2
path: src/bref/src/Lambda/LambdaClient.php

-
message: "#^Function frankenphp_handle_request not found\\.$#"
count: 1
path: src/frankenphp-symfony/src/Runner.php
5 changes: 4 additions & 1 deletion psalm.baseline.xml
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<files psalm-version="4.22.0@fc2c6ab4d5fa5d644d8617089f012f3bb84b8703">
<files psalm-version="4.29.0@7ec5ffbd5f68ae03782d7fd33fff0c45a69f95b3">
<file src="src/bref/src/SymfonyRequestBridge.php">
<InvalidArgument occurrences="1">
<code>$response-&gt;headers-&gt;all()</code>
</InvalidArgument>
</file>
<file src="src/frankenphp-symfony/src/Runner.php">
<UndefinedFunction occurrences="1"/>
</file>
<file src="src/google-cloud/router.php">
<MissingFile occurrences="1">
<code>require_once $_SERVER['SCRIPT_FILENAME'] = $defaultSource</code>
Expand Down
3 changes: 3 additions & 0 deletions src/frankenphp-symfony/.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]
2 changes: 2 additions & 0 deletions src/frankenphp-symfony/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/vendor/
composer.lock
5 changes: 5 additions & 0 deletions src/frankenphp-symfony/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 src/frankenphp-symfony/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.
40 changes: 40 additions & 0 deletions src/frankenphp-symfony/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# FrankenPHP Runtime for Symfony

A runtime for [FrankenPHP](https://frankenphp.dev/).

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/frankenphp-symfony
```

## Usage

Define the environment variable `APP_RUNTIME` for your application.

```
// .env
APP_RUNTIME=Runtime\FrankenPhpSymfony\Runtime
```

```
// .rr.yaml
server:
...
env:
APP_RUNTIME: Runtime\FrankenPhpSymfony\Runtime
```

```php
// public/index.php

use App\Kernel;

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

return function (array $context) {
return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};
```
38 changes: 38 additions & 0 deletions src/frankenphp-symfony/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "runtime/frankenphp-symfony",
"description": "FrankenPHP runtime for Symfony",
"license": "MIT",
"type": "library",
"authors": [
{
"name": "Kévin Dunglas",
"email": "kevin@dunglas.dev"
}
],
"require": {
"php": ">=8.2.0",
"symfony/dependency-injection": "^5.4 || ^6.0",
"symfony/http-kernel": "^5.4 || ^6.0",
"symfony/runtime": "^5.4 || ^6.0"
},
"require-dev": {
"phpunit/phpunit": "^9.5"
},
"minimum-stability": "dev",
"prefer-stable": true,
"autoload": {
"psr-4": {
"Runtime\\FrankenPhpSymfony\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Runtime\\FrankenPhpSymfony\\Tests\\": "tests/"
}
},
"config": {
"allow-plugins": {
"symfony/runtime": true
}
}
}
18 changes: 18 additions & 0 deletions src/frankenphp-symfony/phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/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="Test Suite">
<directory>./tests</directory>
</testsuite>
</testsuites>
</phpunit>
47 changes: 47 additions & 0 deletions src/frankenphp-symfony/src/Runner.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

declare(strict_types=1);

namespace Runtime\FrankenPhpSymfony;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;
use Symfony\Component\Runtime\RunnerInterface;

/**
* A runner for FrankenPHP.
*
* @author Kévin Dunglas <kevin@dunglas.dev>
*/
class Runner implements RunnerInterface
{
private HttpKernelInterface $kernel;

public function __construct(HttpKernelInterface $kernel)
{
$this->kernel = $kernel;
}

public function run(): int
{
$server = array_filter($_SERVER, static fn (string $key) => !str_starts_with($key, 'HTTP_'), ARRAY_FILTER_USE_KEY);
do {
$ret = \frankenphp_handle_request(function () use ($server, &$sfRequest, &$sfResponse): void {
// Merge the environment variables coming from DotEnv with the ones tight to the current request
$_SERVER += $server;

$sfRequest = Request::createFromGlobals();
$sfResponse = $this->kernel->handle($sfRequest);

$sfResponse->send();
});

if ($this->kernel instanceof TerminableInterface && $sfRequest && $sfResponse) {
$this->kernel->terminate($sfRequest, $sfResponse);
}
Comment on lines +40 to +42
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this part not be also inside the frankenphp_handle_request. Or does it have no difference here? If its inside or outside the callable. I'm not sure if the terminate is this way called for every request as it should, else I know some projects which would crash into unexpected state.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Frankenphp only cares about putting out the response. A "cleanup" or background process could be running outside IMHO.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if the terminate is this way called for every request as it should

It does.

} while ($ret);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for the review but maybe the callable could define its return type : void if I'm right, same for the first one:

$server = array_filter($_SERVER, static fn (string $key): bool => !str_starts_with($key, 'HTTP_'), ARRAY_FILTER_USE_KEY);

I'm not sure if the current lib tend to define return types on callable 🙁

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I usually dont add return types on callables. It gives zero to little benefit. But it is just a matter of taste. As long as CI is not complaining, Im fine with adding return types.


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

declare(strict_types=1);

namespace Runtime\FrankenPhpSymfony;

use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Runtime\RunnerInterface;
use Symfony\Component\Runtime\SymfonyRuntime;

/**
* A runtime for FrankenPHP.
*
* @author Kévin Dunglas <kevin@dunglas.dev>
*/
class Runtime extends SymfonyRuntime
{
public function getRunner(?object $application): RunnerInterface
{
if ($application instanceof HttpKernelInterface && ($_SERVER['FRANKENPHP_WORKER'] ?? false)) {
return new Runner($application);
}

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

declare(strict_types=1);

namespace Runtime\FrankenPhpSymfony\Tests;

require_once __DIR__.'/function-mock.php';

use PHPUnit\Framework\TestCase;
use Runtime\FrankenPhpSymfony\Runner;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;

interface TestAppInterface extends HttpKernelInterface, TerminableInterface
{
}

/**
* @author Kévin Dunglas <kevin@dunglas.fr>
*/
class RunnerTest extends TestCase
{
public function testRun(): void
{
$application = $this->createMock(TestAppInterface::class);
$application
->expects($this->once())
->method('handle')
->willReturnCallback(function (Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true): Response {
$this->assertSame('bar', $request->server->get('FOO'));

return new Response();
});
$application->expects($this->once())->method('terminate');

$_SERVER['FOO'] = 'bar';

$runner = new Runner($application);
$this->assertSame(0, $runner->run());
}
}
28 changes: 28 additions & 0 deletions src/frankenphp-symfony/tests/RuntimeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Runtime\FrankenPhpSymfony\Tests;

use PHPUnit\Framework\TestCase;
use Runtime\FrankenPhpSymfony\Runner;
use Runtime\FrankenPhpSymfony\Runtime;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
* @author Kévin Dunglas <kevin@dunglas.dev>
*/
final class RuntimeTest extends TestCase
{
public function testGetRunner(): void
{
$application = $this->createStub(HttpKernelInterface::class);

$runtime = new Runtime();
$this->assertNotInstanceOf(Runner::class, $runtime->getRunner(null));
$this->assertNotInstanceOf(Runner::class, $runtime->getRunner($application));

$_SERVER['FRANKENPHP_WORKER'] = 1;
$this->assertInstanceOf(Runner::class, $runtime->getRunner($application));
}
}
10 changes: 10 additions & 0 deletions src/frankenphp-symfony/tests/function-mock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

if (!function_exists('frankenphp_handle_request')) {
function frankenphp_handle_request(callable $callable): bool
{
$callable();

return false;
}
}