Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[DI] dump factory files as classes #36193

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 31, 2020
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 @@ -142,6 +142,10 @@ public function registerContainerConfiguration(LoaderInterface $loader)
}

$container->setAlias(static::class, 'kernel')->setPublic(true);

if (!$container->hasParameter('container.dumper.inline_factories')) {
$container->setParameter('container.dumper.inline_factories', false);
Copy link
Contributor

Choose a reason for hiding this comment

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

wouldn't it be better to default container.dumper.inline_factories to false when the parameter is not given? you changed this to true in https://github.com/symfony/symfony/pull/34872/files#diff-f7b23d463cba27ac5e4cb677f2be7623R154. so just reverting this would make the default behavior as wanted or?

}
});
}

Expand Down
134 changes: 71 additions & 63 deletions src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class PhpDumper extends Dumper
private $variableCount;
private $inlinedDefinitions;
private $serviceCalls;
private $reservedVariables = ['instance', 'class', 'this'];
private $reservedVariables = ['instance', 'class', 'this', 'container'];
private $expressionLanguage;
private $targetDirRegex;
private $targetDirMaxMatches;
Expand Down Expand Up @@ -246,20 +246,24 @@ public function dump(array $options = [])
if ($this->addGetService) {
$code = preg_replace(
"/(\r?\n\r?\n public function __construct.+?\\{\r?\n)/s",
"\n private \$getService;$1 \$this->getService = \\Closure::fromCallable([\$this, 'getService']);\n",
"\n protected \$getService;$1 \$this->getService = \\Closure::fromCallable([\$this, 'getService']);\n",
$code,
1
);
}

if ($this->asFiles) {
$fileStart = <<<EOF
$fileTemplate = <<<EOF
<?php

use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;

// This file has been auto-generated by the Symfony Dependency Injection Component for internal use.
/*{$this->docStar}
* @internal This class has been auto-generated by the Symfony Dependency Injection Component.
*/
class %s extends {$options['class']}
{%s}

EOF;
$files = [];
Expand All @@ -281,7 +285,7 @@ public function dump(array $options = [])

if (!$this->inlineFactories) {
foreach ($this->generateServiceFiles($services) as $file => $c) {
$files[$file] = $fileStart.$c;
$files[$file] = sprintf($fileTemplate, substr($file, 0, -4), $c);
}
foreach ($proxyClasses as $file => $c) {
$files[$file] = "<?php\n".$c;
Expand All @@ -301,10 +305,8 @@ public function dump(array $options = [])
$code = [];

foreach ($files as $file => $c) {
$code["Container{$hash}/{$file}"] = $c;
$code["Container{$hash}/{$file}"] = substr_replace($c, "<?php\n\nnamespace Container{$hash};\n", 0, 6);
}
array_pop($code);
$code["Container{$hash}/{$options['class']}.php"] = substr_replace($files[$options['class'].'.php'], "<?php\n\nnamespace Container{$hash};\n", 0, 6);
$namespaceLine = $this->namespace ? "\nnamespace {$this->namespace};\n" : '';
$time = $options['build_time'];
$id = hash('crc32', $hash.$time);
Expand All @@ -313,6 +315,9 @@ public function dump(array $options = [])
if ($this->preload && null !== $autoloadFile = $this->getAutoloadFile()) {
$autoloadFile = substr($this->export($autoloadFile), 2, -1);

$factoryFiles = array_reverse(array_keys($code));
$factoryFiles = implode("';\nrequire __DIR__.'/", $factoryFiles);

$code[$options['class'].'.preload.php'] = <<<EOF
<?php

Expand All @@ -322,7 +327,7 @@ public function dump(array $options = [])
use Symfony\Component\DependencyInjection\Dumper\Preloader;

require $autoloadFile;
require __DIR__.'/Container{$hash}/{$options['class']}.php';
require __DIR__.'/$factoryFiles';

\$classes = [];

Expand Down Expand Up @@ -546,7 +551,13 @@ private function generateProxyClasses(): array
$proxyCode = substr(Kernel::stripComments($proxyCode), 5);
}

$proxyClasses[sprintf('%s.php', explode(' ', $this->inlineRequires ? substr($proxyCode, \strlen($code)) : $proxyCode, 3)[1])] = $proxyCode;
$proxyClass = explode(' ', $this->inlineRequires ? substr($proxyCode, \strlen($code)) : $proxyCode, 3)[1];

if ($this->asFiles || $this->namespace) {
$proxyCode .= "\n\\class_alias(__NAMESPACE__.'\\\\$proxyClass', '$proxyClass', false);\n";
}

$proxyClasses[$proxyClass.'.php'] = $proxyCode;
}

return $proxyClasses;
Expand Down Expand Up @@ -784,34 +795,35 @@ private function addService(string $id, Definition $definition): array
$shared = $definition->isShared() ? ' shared' : '';
$public = $definition->isPublic() ? 'public' : 'private';
$autowired = $definition->isAutowired() ? ' autowired' : '';
$asFile = $this->asFiles && !$this->inlineFactories && !$this->isHotPath($definition);
$methodName = $this->generateMethodName($id);

if ($definition->isLazy()) {
if ($asFile || $definition->isLazy()) {
$lazyInitialization = '$lazyLoad = true';
} else {
$lazyInitialization = '';
}

$asFile = $this->asFiles && !$this->inlineFactories && !$this->isHotPath($definition);
$methodName = $this->generateMethodName($id);
if ($asFile) {
$file = $methodName.'.php';
$code = " // Returns the $public '$id'$shared$autowired service.\n\n";
} else {
$file = null;
$code = <<<EOF
$code = <<<EOF

/*{$this->docStar}
* Gets the $public '$id'$shared$autowired service.
*
* $return
EOF;
$code = str_replace('*/', ' ', $code).<<<EOF
$code = str_replace('*/', ' ', $code).<<<EOF

*/
protected function {$methodName}($lazyInitialization)
{

EOF;

if ($asFile) {
$file = $methodName.'.php';
$code = str_replace("protected function {$methodName}(", 'public static function do($container, ', $code);
} else {
$file = null;
}

if ($definition->hasErrors() && $e = $definition->getErrors()) {
Expand All @@ -833,20 +845,21 @@ protected function {$methodName}($lazyInitialization)
}

if ($this->getProxyDumper()->isProxyCandidate($definition)) {
$factoryCode = $asFile ? ($definition->isShared() ? "\$this->load('%s.php', false)" : '$this->factories[%2$s](false)') : '$this->%s(false)';
$code .= $this->getProxyDumper()->getProxyFactoryCode($definition, $id, sprintf($factoryCode, $methodName, $this->doExport($id)));
$factoryCode = $asFile ? "\$this->load('%s', false)" : '$this->%s(false)';
$code .= $this->getProxyDumper()->getProxyFactoryCode($definition, $id, sprintf($factoryCode, $methodName));
}

$code .= $this->addServiceInclude($id, $definition);
$code .= $this->addInlineService($id, $definition);
}

if ($asFile) {
$code = implode("\n", array_map(function ($line) { return $line ? substr($line, 8) : $line; }, explode("\n", $code)));
} else {
$code .= " }\n";
$code = str_replace('$this', '$container', $code);
$code = str_replace('function () {', 'function () use ($container) {', $code);
}

$code .= " }\n";

$this->definitionVariables = $this->inlinedDefinitions = null;
$this->referenceVariables = $this->serviceCalls = null;

Expand Down Expand Up @@ -1017,21 +1030,6 @@ private function generateServiceFiles(array $services): iterable
ksort($definitions);
foreach ($definitions as $id => $definition) {
if ((list($file, $code) = $services[$id]) && null !== $file && ($definition->isPublic() || !$this->isTrivialInstance($definition) || isset($this->locatedIds[$id]))) {
if (!$definition->isShared()) {
$i = strpos($code, "\n\ninclude_once ");
if (false !== $i && false !== $i = strpos($code, "\n\n", 2 + $i)) {
$code = [substr($code, 0, 2 + $i), substr($code, 2 + $i)];
} else {
$code = ["\n", $code];
}
$code[1] = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code[1])));
$factory = sprintf('$this->factories%s[%s]', $definition->isPublic() ? '' : "['service_container']", $this->doExport($id));
$lazyloadInitialization = $definition->isLazy() ? '$lazyLoad = true' : '';

$code[1] = sprintf("%s = function (%s) {\n%s};\n\nreturn %1\$s();\n", $factory, $lazyloadInitialization, $code[1]);
$code = $code[0].$code[1];
}

yield $file => $code;
}
}
Expand Down Expand Up @@ -1112,27 +1110,24 @@ private function startClass(string $class, string $baseClass): string
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

/*{$this->docStar}
* This class has been auto-generated
* by the Symfony Dependency Injection Component.
*
* @final
* @internal This class has been auto-generated by the Symfony Dependency Injection Component.
*/
class $class extends $baseClass
{
private \$parameters = [];
protected \$parameters = [];

public function __construct()
{

EOF;
if ($this->asFiles) {
$code = str_replace('$parameters', "\$buildParameters;\n private \$containerDir;\n private \$parameters", $code);
$code = str_replace('$parameters = []', "\$containerDir;\n protected \$parameters = [];\n private \$buildParameters", $code);
$code = str_replace('__construct()', '__construct(array $buildParameters = [], $containerDir = __DIR__)', $code);
$code .= " \$this->buildParameters = \$buildParameters;\n";
$code .= " \$this->containerDir = \$containerDir;\n";

if (null !== $this->targetDirRegex) {
$code = str_replace('$parameters', "\$targetDir;\n private \$parameters", $code);
$code = str_replace('$parameters = []', "\$targetDir;\n protected \$parameters = []", $code);
$code .= ' $this->targetDir = \\dirname($containerDir);'."\n";
}
}
Expand Down Expand Up @@ -1176,11 +1171,23 @@ public function isCompiled(): bool
$code .= $this->addRemovedIds();

if ($this->asFiles && !$this->inlineFactories) {
$code .= <<<EOF
$code .= <<<'EOF'

protected function load(\$file, \$lazyLoad = true)
protected function load($file, $lazyLoad = true)
{
return require \$this->containerDir.\\DIRECTORY_SEPARATOR.\$file;
if (class_exists($class = __NAMESPACE__.'\\'.$file, false)) {
return $class::do($this, $lazyLoad);
}

if ('.' === $file[-4]) {
$class = substr($class, 0, -4);
} else {
$file .= '.php';
}

$service = require $this->containerDir.\DIRECTORY_SEPARATOR.$file;

return class_exists($class, false) ? $class::do($this, $lazyLoad) : $service;
}

EOF;
Expand All @@ -1191,16 +1198,13 @@ protected function load(\$file, \$lazyLoad = true)
if (!$proxyDumper->isProxyCandidate($definition)) {
continue;
}

if ($this->asFiles && !$this->inlineFactories) {
$proxyLoader = '$this->load("{$class}.php")';
} elseif ($this->namespace || $this->inlineFactories) {
$proxyLoader = 'class_alias(__NAMESPACE__."\\\\$class", $class, false)';
$proxyLoader = "class_exists(\$class, false) || require __DIR__.'/'.\$class.'.php';\n\n ";
} else {
$proxyLoader = '';
}
if ($proxyLoader) {
$proxyLoader = "class_exists(\$class, false) || {$proxyLoader};\n\n ";
}

$code .= <<<EOF

protected function createProxy(\$class, \Closure \$factory)
Expand Down Expand Up @@ -1295,7 +1299,7 @@ private function addFileMap(): string
ksort($definitions);
foreach ($definitions as $id => $definition) {
if (!$definition->isSynthetic() && $definition->isPublic() && !$this->isHotPath($definition)) {
$code .= sprintf(" %s => '%s.php',\n", $this->doExport($id), $this->generateMethodName($id));
$code .= sprintf(" %s => '%s',\n", $this->doExport($id), $this->generateMethodName($id));
}
}

Expand Down Expand Up @@ -1709,7 +1713,7 @@ private function dumpValue($value, bool $interpolate = true): string
$this->export($k),
$this->export($definition->isShared() ? ($definition->isPublic() ? 'services' : 'privates') : false),
$this->doExport($id),
$this->export(ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE !== $v->getInvalidBehavior() && !\is_string($load) ? $this->generateMethodName($id).($load ? '.php' : '') : null),
$this->export(ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE !== $v->getInvalidBehavior() && !\is_string($load) ? $this->generateMethodName($id) : null),
$this->export($load)
);
$serviceTypes .= sprintf("\n %s => %s,", $this->export($k), $this->export($v instanceof TypedReference ? $v->getType() : '?'));
Expand Down Expand Up @@ -1850,11 +1854,7 @@ private function getServiceCall(string $id, Reference $reference = null): string
}
$code = "($code)";
} elseif ($this->asFiles && !$this->inlineFactories && !$this->isHotPath($definition)) {
$code = sprintf("\$this->load('%s.php')", $this->generateMethodName($id));
if (!$definition->isShared()) {
$factory = sprintf('$this->factories%s[%s]', $definition->isPublic() ? '' : "['service_container']", $this->doExport($id));
$code = sprintf('(isset(%s) ? %1$s() : %s)', $factory, $code);
}
$code = sprintf("\$this->load('%s')", $this->generateMethodName($id));
} else {
$code = sprintf('$this->%s()', $this->generateMethodName($id));
}
Expand Down Expand Up @@ -2045,6 +2045,14 @@ private function doExport($value, bool $resolveEnv = false)
} else {
$export = var_export($value, true);
}
if ($this->asFiles) {
if (false !== strpos($export, '$this')) {
$export = str_replace('$this', "$'.'this", $export);
}
if (false !== strpos($export, 'function () {')) {
$export = str_replace('function () {', "function ('.') {", $export);
}
}

if ($resolveEnv && "'" === $export[0] && $export !== $resolvedExport = $this->container->resolveEnvPlaceholders($export, "'.\$this->getEnv('string:%s').'")) {
$export = $resolvedExport;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,11 @@
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

/**
* This class has been auto-generated
* by the Symfony Dependency Injection Component.
*
* @final
* @internal This class has been auto-generated by the Symfony Dependency Injection Component.
*/
class Symfony_DI_PhpDumper_Test_Aliases_Deprecation extends Container
{
private $parameters = [];
protected $parameters = [];

public function __construct()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,11 @@
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

/**
* This class has been auto-generated
* by the Symfony Dependency Injection Component.
*
* @final
* @internal This class has been auto-generated by the Symfony Dependency Injection Component.
*/
class ProjectServiceContainer extends \Symfony\Component\DependencyInjection\Tests\Fixtures\Container\ConstructorWithoutArgumentsContainer
{
private $parameters = [];
protected $parameters = [];

public function __construct()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,11 @@
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

/**
* This class has been auto-generated
* by the Symfony Dependency Injection Component.
*
* @final
* @internal This class has been auto-generated by the Symfony Dependency Injection Component.
*/
class ProjectServiceContainer extends \Symfony\Component\DependencyInjection\Tests\Fixtures\Container\ConstructorWithMandatoryArgumentsContainer
{
private $parameters = [];
protected $parameters = [];

public function __construct()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,11 @@
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

/**
* This class has been auto-generated
* by the Symfony Dependency Injection Component.
*
* @final
* @internal This class has been auto-generated by the Symfony Dependency Injection Component.
*/
class ProjectServiceContainer extends \Symfony\Component\DependencyInjection\Tests\Fixtures\Container\ConstructorWithOptionalArgumentsContainer
{
private $parameters = [];
protected $parameters = [];

public function __construct()
{
Expand Down
Loading