Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Runtime] a new component to decouple applications from global state #38465

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 10, 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
1 change: 1 addition & 0 deletions 1 .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
/src/Symfony/Component/Mailer/Bridge export-ignore
/src/Symfony/Component/Messenger/Bridge export-ignore
/src/Symfony/Component/Notifier/Bridge export-ignore
/src/Symfony/Component/Runtime export-ignore
1 change: 1 addition & 0 deletions 1 .github/patch-types.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
case false !== strpos($file, '/src/Symfony/Component/ErrorHandler/Tests/Fixtures/'):
case false !== strpos($file, '/src/Symfony/Component/PropertyInfo/Tests/Fixtures/Dummy.php'):
case false !== strpos($file, '/src/Symfony/Component/PropertyInfo/Tests/Fixtures/ParentDummy.php'):
case false !== strpos($file, '/src/Symfony/Component/Runtime/Internal/ComposerPlugin.php'):
case false !== strpos($file, '/src/Symfony/Component/Serializer/Tests/Normalizer/Features/ObjectOuter.php'):
case false !== strpos($file, '/src/Symfony/Component/VarDumper/Tests/Fixtures/NotLoadableClass.php'):
continue 2;
Expand Down
7 changes: 6 additions & 1 deletion 7 composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@
"symfony/polyfill-mbstring": "~1.0",
"symfony/polyfill-php73": "^1.11",
"symfony/polyfill-php80": "^1.15",
"symfony/polyfill-uuid": "^1.15"
"symfony/polyfill-uuid": "^1.15",
"symfony/runtime": "self.version"
},
"replace": {
"symfony/asset": "self.version",
Expand Down Expand Up @@ -193,6 +194,10 @@
"symfony/contracts": "2.4.x-dev"
}
}
},
{
"type": "path",
"url": "src/Symfony/Component/Runtime"
}
],
"minimum-stability": "dev"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\HttpKernel\UriSigner;
use Symfony\Component\Runtime\SymfonyRuntime;
use Symfony\Component\String\LazyString;
use Symfony\Component\String\Slugger\AsciiSlugger;
use Symfony\Component\String\Slugger\SluggerInterface;
Expand Down Expand Up @@ -78,6 +79,7 @@ class_exists(WorkflowEvents::class) ? WorkflowEvents::ALIASES : []
service('argument_resolver'),
])
->tag('container.hot_path')
->tag('container.preload', ['class' => SymfonyRuntime::class])
->alias(HttpKernelInterface::class, 'http_kernel')

->set('request_stack', RequestStack::class)
Expand Down
4 changes: 4 additions & 0 deletions 4 src/Symfony/Component/Runtime/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
3 changes: 3 additions & 0 deletions 3 src/Symfony/Component/Runtime/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml
7 changes: 7 additions & 0 deletions 7 src/Symfony/Component/Runtime/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

5.3.0
-----

* Add the component
170 changes: 170 additions & 0 deletions 170 src/Symfony/Component/Runtime/GenericRuntime.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
<?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\Component\Runtime;

use Symfony\Component\Runtime\Internal\BasicErrorHandler;
use Symfony\Component\Runtime\Resolver\ClosureResolver;
use Symfony\Component\Runtime\Resolver\DebugClosureResolver;
use Symfony\Component\Runtime\Runner\ClosureRunner;

// Help opcache.preload discover always-needed symbols
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.
*
* The app-callable can declare arguments among either:
* - "array $context" to get a local array similar to $_SERVER;
* - "array $argv" to get the command line arguments when running on the CLI;
* - "array $request" to get a local array with keys "query", "body", "files" and
* "session", which map to $_GET, $_POST, $FILES and &$_SESSION respectively.
*
* It should return a Closure():int|string|null or an instance of RunnerInterface.
*
* In debug mode, the runtime registers a strict error handler
* that throws exceptions when a PHP warning/notice is raised.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @experimental in 5.3
*/
class GenericRuntime implements RuntimeInterface
{
private $debug;

/**
* @param array {
* debug?: ?bool,
* } $options
*/
public function __construct(array $options = [])
{
$this->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 ($this->debug) {
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = '1';
$errorHandler = new BasicErrorHandler($this->debug);
set_error_handler($errorHandler);
} else {
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = '0';
}
}

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

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

$arguments = function () use ($parameters) {
$arguments = [];

try {
foreach ($parameters as $parameter) {
$type = $parameter->getType();
$arguments[] = $this->getArgument($parameter, $type instanceof \ReflectionNamedType ? $type->getName() : null);
}
} catch (\InvalidArgumentException $e) {
if (!$parameter->isOptional()) {
throw $e;
}
}

return $arguments;
};

if ($this->debug) {
return new DebugClosureResolver($callable, $arguments);
}

return new ClosureResolver($callable, $arguments);
}

/**
* {@inheritdoc}
*/
public function getRunner(?object $application): RunnerInterface
{
if (null === $application) {
$application = static function () { return 0; };
}

if ($application instanceof 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) {
$application = \Closure::fromCallable($application);
}

if ($this->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()));
}

return new ClosureRunner($application);
}

/**
* @return mixed
*/
protected function getArgument(\ReflectionParameter $parameter, ?string $type)
{
if ('array' === $type) {
switch ($parameter->name) {
case 'context':
$context = $_SERVER;

if ($_ENV && !isset($_SERVER['PATH']) && !isset($_SERVER['Path'])) {
$context += $_ENV;
}

return $context;

case 'argv':
return $_SERVER['argv'] ?? [];

case 'request':
return [
'query' => $_GET,
'body' => $_POST,
'files' => $_FILES,
'session' => &$_SESSION,
];
}
}

if (RuntimeInterface::class === $type) {
return $this;
}

$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".', $type, $parameter->name, $r->getFileName(), $r->getStartLine(), get_debug_type($this)));
}
}
53 changes: 53 additions & 0 deletions 53 src/Symfony/Component/Runtime/Internal/BasicErrorHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?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\Component\Runtime\Internal;

/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
class BasicErrorHandler
{
public function __construct(bool $debug)
{
error_reporting(-1);

if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) {
ini_set('display_errors', $debug);
} elseif (!filter_var(ini_get('log_errors'), \FILTER_VALIDATE_BOOLEAN) || ini_get('error_log')) {
// CLI - display errors only if they're not already logged to STDERR
ini_set('display_errors', 1);
}

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);
}
}

public function __invoke(int $type, string $message, string $file, int $line): bool
{
if ((\E_DEPRECATED | \E_USER_DEPRECATED) & $type) {
return true;
}

if ((error_reporting() | \E_ERROR | \E_RECOVERABLE_ERROR | \E_PARSE | \E_CORE_ERROR | \E_COMPILE_ERROR | \E_USER_ERROR) & $type) {
throw new \ErrorException($message, 0, $type, $file, $line);
}

return false;
}
}
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.