Skip to content

[Runtime] make GenericRuntime ... generic #40513

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 1 commit into from
Mar 19, 2021
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
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\HttpKernel\UriSigner;
use Symfony\Component\Runtime\Runner\Symfony\HttpKernelRunner;
use Symfony\Component\Runtime\Runner\Symfony\ResponseRunner;
use Symfony\Component\Runtime\SymfonyRuntime;
use Symfony\Component\String\LazyString;
use Symfony\Component\String\Slugger\AsciiSlugger;
Expand Down Expand Up @@ -79,6 +81,8 @@ class_exists(WorkflowEvents::class) ? WorkflowEvents::ALIASES : []
service('argument_resolver'),
])
->tag('container.hot_path')
->tag('container.preload', ['class' => HttpKernelRunner::class])
->tag('container.preload', ['class' => ResponseRunner::class])
->tag('container.preload', ['class' => SymfonyRuntime::class])
->alias(HttpKernelInterface::class, 'http_kernel')

Expand Down
104 changes: 83 additions & 21 deletions src/Symfony/Component/Runtime/GenericRuntime.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,12 @@ class_exists(ClosureResolver::class);
/**
* A runtime to do bare-metal PHP without using superglobals.
*
* One option named "debug" is supported; it toggles displaying errors
* and defaults to the "APP_ENV" environment variable.
* It supports the following options:
* - "debug" toggles displaying errors and defaults
* to the "APP_DEBUG" environment variable;
* - "runtimes" maps types to a GenericRuntime implementation
* that knows how to deal with each of them;
* - "error_handler" defines the class to use to handle PHP errors.
*
* The app-callable can declare arguments among either:
* - "array $context" to get a local array similar to $_SERVER;
Expand All @@ -42,42 +46,48 @@ class_exists(ClosureResolver::class);
*/
class GenericRuntime implements RuntimeInterface
{
private $debug;
protected $options;

/**
* @param array {
* debug?: ?bool,
* runtimes?: ?array,
* error_handler?: string|false,
* } $options
*/
public function __construct(array $options = [])
{
$this->debug = $options['debug'] ?? $_SERVER['APP_DEBUG'] ?? $_ENV['APP_DEBUG'] ?? true;
$debug = $options['debug'] ?? $_SERVER['APP_DEBUG'] ?? $_ENV['APP_DEBUG'] ?? true;

if (!\is_bool($this->debug)) {
$this->debug = filter_var($this->debug, \FILTER_VALIDATE_BOOLEAN);
if (!\is_bool($debug)) {
$debug = filter_var($debug, \FILTER_VALIDATE_BOOLEAN);
}

if ($this->debug) {
if ($debug) {
umask(0000);
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = '1';
$errorHandler = new BasicErrorHandler($this->debug);
set_error_handler($errorHandler);

if (false !== $errorHandler = ($options['error_handler'] ?? BasicErrorHandler::class)) {
$errorHandler::register($debug);
$options['error_handler'] = false;
}
} else {
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = '0';
}

$this->options = $options;
}

/**
* {@inheritdoc}
*/
public function getResolver(callable $callable): ResolverInterface
public function getResolver(callable $callable, \ReflectionFunction $reflector = null): ResolverInterface
{
if (!$callable instanceof \Closure) {
$callable = \Closure::fromCallable($callable);
}

$function = new \ReflectionFunction($callable);
$parameters = $function->getParameters();

$parameters = ($reflector ?? new \ReflectionFunction($callable))->getParameters();
$arguments = function () use ($parameters) {
$arguments = [];

Expand All @@ -95,7 +105,7 @@ public function getResolver(callable $callable): ResolverInterface
return $arguments;
};

if ($this->debug) {
if ($_SERVER['APP_DEBUG']) {
return new DebugClosureResolver($callable, $arguments);
}

Expand All @@ -115,15 +125,19 @@ public function getRunner(?object $application): RunnerInterface
return $application;
}

if (!\is_callable($application)) {
throw new \LogicException(sprintf('"%s" doesn\'t know how to handle apps of type "%s".', get_debug_type($this), get_debug_type($application)));
}

if (!$application instanceof \Closure) {
if ($runtime = $this->resolveRuntime(\get_class($application))) {
return $runtime->getRunner($application);
}

if (!\is_callable($application)) {
throw new \LogicException(sprintf('"%s" doesn\'t know how to handle apps of type "%s".', get_debug_type($this), get_debug_type($application)));
}

$application = \Closure::fromCallable($application);
}

if ($this->debug && ($r = new \ReflectionFunction($application)) && $r->getNumberOfRequiredParameters()) {
if ($_SERVER['APP_DEBUG'] && ($r = new \ReflectionFunction($application)) && $r->getNumberOfRequiredParameters()) {
throw new \ArgumentCountError(sprintf('Zero argument should be required by the runner callable, but at least one is in "%s" on line "%d.', $r->getFileName(), $r->getStartLine()));
}

Expand Down Expand Up @@ -163,8 +177,56 @@ protected function getArgument(\ReflectionParameter $parameter, ?string $type)
return $this;
}

$r = $parameter->getDeclaringFunction();
if (!$runtime = $this->getRuntime($type)) {
$r = $parameter->getDeclaringFunction();

throw new \InvalidArgumentException(sprintf('Cannot resolve argument "%s $%s" in "%s" on line "%d": "%s" supports only arguments "array $context", "array $argv" and "array $request", or a runtime named "Symfony\Runtime\%1$sRuntime".', $type, $parameter->name, $r->getFileName(), $r->getStartLine(), get_debug_type($this)));
}

return $runtime->getArgument($parameter, $type);
}

protected static function register(self $runtime): self
{
return $runtime;
}

private function getRuntime(string $type): ?self
{
if (null === $runtime = ($this->options['runtimes'][$type] ?? null)) {
$runtime = 'Symfony\Runtime\\'.$type.'Runtime';
$runtime = class_exists($runtime) ? $runtime : $this->options['runtimes'][$type] = false;
}

if (\is_string($runtime)) {
$runtime = $runtime::register($this);
}

if ($this === $runtime) {
return null;
}

return $runtime ?: null;
}

private function resolveRuntime(string $class): ?self
{
if ($runtime = $this->getRuntime($class)) {
return $runtime;
}

foreach (class_parents($class) as $type) {
if ($runtime = $this->getRuntime($type)) {
return $runtime;
}
}

foreach (class_implements($class) as $type) {
if ($runtime = $this->getRuntime($type)) {
return $runtime;
}
}

throw new \InvalidArgumentException(sprintf('Cannot resolve argument "%s $%s" in "%s" on line "%d": "%s" supports only arguments "array $context", "array $argv" and "array $request".', $type, $parameter->name, $r->getFileName(), $r->getStartLine(), get_debug_type($this)));
return null;
}
}
5 changes: 3 additions & 2 deletions src/Symfony/Component/Runtime/Internal/BasicErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
*/
class BasicErrorHandler
{
public function __construct(bool $debug)
public static function register(bool $debug): void
{
error_reporting(-1);

Expand All @@ -32,10 +32,11 @@ public function __construct(bool $debug)
if (0 <= ini_get('zend.assertions')) {
ini_set('zend.assertions', 1);
ini_set('assert.active', $debug);
ini_set('assert.bail', 0);
ini_set('assert.warning', 0);
ini_set('assert.exception', 1);
}

set_error_handler(new self());
}

public function __invoke(int $type, string $message, string $file, int $line): bool
Expand Down
6 changes: 2 additions & 4 deletions src/Symfony/Component/Runtime/Internal/ComposerPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,14 +102,12 @@ public function updateAutoloadFile(): void
throw new \InvalidArgumentException(sprintf('Class "%s" listed under "extra.runtime.class" in your composer.json file '.(class_exists($runtimeClass) ? 'should implement "%s".' : 'not found.'), $runtimeClass, RuntimeInterface::class));
}

if (!\is_array($runtimeOptions = $extra['options'] ?? [])) {
throw new \InvalidArgumentException('The "extra.runtime.options" entry in your composer.json file must be an array.');
}
unset($extra['class'], $extra['autoload_template']);

$code = strtr(file_get_contents($autoloadTemplate), [
'%project_dir%' => $projectDir,
'%runtime_class%' => var_export($runtimeClass, true),
'%runtime_options%' => '['.substr(var_export($runtimeOptions, true), 7, -1)." 'project_dir' => {$projectDir},\n]",
'%runtime_options%' => '['.substr(var_export($extra, true), 7, -1)." 'project_dir' => {$projectDir},\n]",
]);

file_put_contents(substr_replace($autoloadFile, '_runtime', -4, 0), $code);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Runtime\Symfony\Component\Console;

use Symfony\Component\Runtime\SymfonyRuntime;

/**
* @internal
*/
class ApplicationRuntime extends SymfonyRuntime
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Runtime\Symfony\Component\Console\Command;

use Symfony\Component\Runtime\SymfonyRuntime;

/**
* @internal
*/
class CommandRuntime extends SymfonyRuntime
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Runtime\Symfony\Component\Console\Input;

use Symfony\Component\Runtime\SymfonyRuntime;

/**
* @internal
*/
class InputInterfaceRuntime extends SymfonyRuntime
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Runtime\Symfony\Component\Console\Output;

use Symfony\Component\Runtime\SymfonyRuntime;

/**
* @internal
*/
class OutputInterfaceRuntime extends SymfonyRuntime
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Runtime\Symfony\Component\HttpFoundation;

use Symfony\Component\Runtime\SymfonyRuntime;

/**
* @internal
*/
class RequestRuntime extends SymfonyRuntime
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Runtime\Symfony\Component\HttpFoundation;

use Symfony\Component\Runtime\SymfonyRuntime;

/**
* @internal
*/
class ResponseRuntime extends SymfonyRuntime
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Runtime\Symfony\Component\HttKernel;

use Symfony\Component\Runtime\SymfonyRuntime;

/**
* @internal
*/
class HttpKernelInterfaceRuntime extends SymfonyRuntime
{
}
Loading