Skip to content

Commit

Permalink
bug #34920 [Routing] fix memoryleak when loading compiled routes (nic…
Browse files Browse the repository at this point in the history
…olas-grekas)

This PR was merged into the 4.3 branch.

Discussion
----------

[Routing] fix memoryleak when loading compiled routes

| Q             | A
| ------------- | ---
| Branch?       | 4.3
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       | -
| License       | MIT
| Doc PR        | -

Same as #34918 for Routing. That's the last significant memory hog I've identified.

Commits
-------

85371a1 [Routing] fix memoryleak when loading compiled routes
  • Loading branch information
fabpot committed Dec 11, 2019
2 parents 3df1d1e + 85371a1 commit ebadf51
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions src/Symfony/Component/Routing/Router.php
Expand Up @@ -97,6 +97,8 @@ class Router implements RouterInterface, RequestMatcherInterface
*/
private $expressionLanguageProviders = [];

private static $cache = [];

/**
* @param LoaderInterface $loader A LoaderInterface instance
* @param mixed $resource The main resource to load
Expand Down Expand Up @@ -325,7 +327,7 @@ function (ConfigCacheInterface $cache) {
);

if ($compiled) {
return $this->matcher = new $this->options['matcher_class'](require $cache->getPath(), $this->context);
return $this->matcher = new $this->options['matcher_class'](self::getCompiledRoutes($cache->getPath()), $this->context);
}

if (!class_exists($this->options['matcher_cache_class'], false)) {
Expand Down Expand Up @@ -369,7 +371,7 @@ function (ConfigCacheInterface $cache) {
);

if ($compiled) {
$this->generator = new $this->options['generator_class'](require $cache->getPath(), $this->context, $this->logger, $this->defaultLocale);
$this->generator = new $this->options['generator_class'](self::getCompiledRoutes($cache->getPath()), $this->context, $this->logger, $this->defaultLocale);
} else {
if (!class_exists($this->options['generator_cache_class'], false)) {
require_once $cache->getPath();
Expand Down Expand Up @@ -442,4 +444,21 @@ private function checkDeprecatedOption($key)
@trigger_error(sprintf('Option "%s" given to router %s is deprecated since Symfony 4.3.', $key, static::class), E_USER_DEPRECATED);
}
}

private static function getCompiledRoutes(string $path): array
{
if ([] === self::$cache && \function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN) && (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) || filter_var(ini_get('opcache.enable_cli'), FILTER_VALIDATE_BOOLEAN))) {
self::$cache = null;
}

if (null === self::$cache) {
return require $path;
}

if (isset(self::$cache[$path])) {
return self::$cache[$path];
}

return self::$cache[$path] = require $path;
}
}

0 comments on commit ebadf51

Please sign in to comment.