Skip to content

Commit

Permalink
minor #33529 [DI] use dirname() when possible (nicolas-grekas)
Browse files Browse the repository at this point in the history
This PR was merged into the 4.4 branch.

Discussion
----------

[DI] use dirname() when possible

| Q             | A
| ------------- | ---
| Branch?       | 4.4
| Bug fix?      | no
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | -
| License       | MIT
| Doc PR        | -

On second look, I think this works :)

Commits
-------

2eae300 [DI] use dirname() when possible
  • Loading branch information
nicolas-grekas committed Sep 10, 2019
2 parents 51ffc18 + 2eae300 commit 541f80c
Show file tree
Hide file tree
Showing 48 changed files with 92 additions and 148 deletions.
75 changes: 53 additions & 22 deletions src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
Expand Up @@ -11,6 +11,8 @@

namespace Symfony\Component\DependencyInjection\Dumper;

use Composer\Autoload\ClassLoader;
use Symfony\Component\Debug\DebugClassLoader as LegacyDebugClassLoader;
use Symfony\Component\DependencyInjection\Argument\ArgumentInterface;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
Expand All @@ -36,6 +38,7 @@
use Symfony\Component\DependencyInjection\ServiceLocator as BaseServiceLocator;
use Symfony\Component\DependencyInjection\TypedReference;
use Symfony\Component\DependencyInjection\Variable;
use Symfony\Component\ErrorHandler\DebugClassLoader;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\HttpKernel\Kernel;

Expand Down Expand Up @@ -296,8 +299,11 @@ public function dump(array $options = [])
$namespaceLine = $this->namespace ? "\nnamespace {$this->namespace};\n" : '';
$time = $options['build_time'];
$id = hash('crc32', $hash.$time);
$this->asFiles = false;

if ($preload && null !== $autoloadFile = $this->getAutoloadFile()) {
$autoloadFile = substr($this->export($autoloadFile), 2, -1);

if ($preload) {
$code[$options['class'].'.preload.php'] = <<<EOF
<?php
Expand All @@ -306,7 +312,7 @@ public function dump(array $options = [])
use Symfony\Component\DependencyInjection\Dumper\Preloader;
require dirname(__DIR__, 3).'/vendor/autoload.php';
require $autoloadFile;
require __DIR__.'/Container{$hash}/{$options['class']}.php';
\$classes = [];
Expand Down Expand Up @@ -511,7 +517,6 @@ private function generateProxyClasses(): array
if ($this->inlineFactories) {
$this->inlinedRequires[$file] = true;
}
$file = preg_replace('#^\\$this->targetDirs\[(\d++)\]#', sprintf('\dirname(__DIR__, %d + $1)', $this->asFiles), $file);
$code .= sprintf("include_once %s;\n", $file);
}

Expand Down Expand Up @@ -553,7 +558,6 @@ private function addServiceInclude(string $cId, Definition $definition): string
}

foreach (array_diff_key(array_flip($lineage), $this->inlinedRequires) as $file => $class) {
$file = preg_replace('#^\\$this->targetDirs\[(\d++)\]#', sprintf('\dirname(__DIR__, %d + $1)', $this->asFiles), $file);
$code .= sprintf(" include_once %s;\n", $file);
}
}
Expand All @@ -562,7 +566,6 @@ private function addServiceInclude(string $cId, Definition $definition): string
if ($file = $def->getFile()) {
$file = $this->dumpValue($file);
$file = '(' === $file[0] ? substr($file, 1, -1) : $file;
$file = preg_replace('#^\\$this->targetDirs\[(\d++)\]#', sprintf('\dirname(__DIR__, %d + $1)', $this->asFiles), $file);
$code .= sprintf(" include_once %s;\n", $file);
}
}
Expand Down Expand Up @@ -1076,27 +1079,21 @@ private function startClass(string $class, string $baseClass, ?array &$preload):
class $class extends $baseClass
{
private \$parameters = [];
private \$targetDirs = [];
public function __construct()
{
EOF;
if (null !== $this->targetDirRegex) {
$dir = $this->asFiles ? '$this->targetDirs[0] = \\dirname($containerDir)' : '__DIR__';
$code .= <<<EOF
\$dir = {$dir};
for (\$i = 1; \$i <= {$this->targetDirMaxMatches}; ++\$i) {
\$this->targetDirs[\$i] = \$dir = \\dirname(\$dir);
}
EOF;
}
if ($this->asFiles) {
$code = str_replace('$parameters', "\$buildParameters;\n private \$containerDir;\n private \$parameters", $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 .= ' $this->targetDir = \\dirname($containerDir);'."\n";
}
}

if (Container::class !== $this->baseClass) {
Expand Down Expand Up @@ -1350,12 +1347,11 @@ private function addInlineRequires(?array &$preload): string
foreach ($lineage as $file) {
if (!isset($this->inlinedRequires[$file])) {
$this->inlinedRequires[$file] = true;
$file = preg_replace('#^\\$this->targetDirs\[(\d++)\]#', sprintf('\dirname(__DIR__, %d + $1)', $this->asFiles), $file);
$code .= sprintf("\n include_once %s;", $file);
}
}

return $code ? sprintf("\n \$this->privates['service_container'] = static function () {%s\n };\n", $code) : '';
return $code ? sprintf("\n \$this->privates['service_container'] = function () {%s\n };\n", $code) : '';
}

private function addDefaultParametersMethod(): string
Expand All @@ -1374,7 +1370,7 @@ private function addDefaultParametersMethod(): string
$export = $this->exportParameters([$value]);
$export = explode('0 => ', substr(rtrim($export, " ]\n"), 2, -1), 2);

if (preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDirs\[\d++\])/", $export[1])) {
if (preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDir\.'')/", $export[1])) {
$dynamicPhp[$key] = sprintf('%scase %s: $value = %s; break;', $export[0], $this->export($key), $export[1]);
} else {
$php[] = sprintf('%s%s => %s,', $export[0], $this->export($key), $export[1]);
Expand Down Expand Up @@ -1776,7 +1772,7 @@ private function dumpParameter(string $name): string
return $dumpedValue;
}

if (!preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDirs\[\d++\])/", $dumpedValue)) {
if (!preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDir\.'')/", $dumpedValue)) {
return sprintf('$this->parameters[%s]', $this->doExport($name));
}
}
Expand Down Expand Up @@ -1977,8 +1973,10 @@ private function export($value)
$dirname = $this->asFiles ? '$this->containerDir' : '__DIR__';
$offset = 1 + $this->targetDirMaxMatches - \count($matches);

if ($this->asFiles || 0 < $offset) {
$dirname = sprintf('$this->targetDirs[%d]', $offset);
if (0 < $offset) {
$dirname = sprintf('\dirname(__DIR__, %d)', $offset + (int) $this->asFiles);
} elseif ($this->asFiles) {
$dirname = "\$this->targetDir.''"; // empty string concatenation on purpose
}

if ($prefix || $suffix) {
Expand Down Expand Up @@ -2027,4 +2025,37 @@ private function doExport($value, bool $resolveEnv = false)

return $export;
}

private function getAutoloadFile(): ?string
{
if (null === $this->targetDirRegex) {
return null;
}

foreach (spl_autoload_functions() as $autoloader) {
if (!\is_array($autoloader)) {
continue;
}

if ($autoloader[0] instanceof DebugClassLoader || $autoloader[0] instanceof LegacyDebugClassLoader) {
$autoloader = $autoloader[0]->getClassLoader();
}

if (!\is_array($autoloader) || !$autoloader[0] instanceof ClassLoader || !$autoloader[0]->findFile(__CLASS__)) {
continue;
}

foreach (get_declared_classes() as $class) {
if (0 === strpos($class, 'ComposerAutoloaderInit') && $class::getLoader() === $autoloader[0]) {
$file = (new \ReflectionClass($class))->getFileName();

if (preg_match($this->targetDirRegex.'A', $file)) {
return $file;
}
}
}
}

return null;
}
}
Expand Up @@ -18,7 +18,6 @@
class Symfony_DI_PhpDumper_Test_Aliases_Deprecation extends Container
{
private $parameters = [];
private $targetDirs = [];

public function __construct()
{
Expand Down
Expand Up @@ -20,7 +20,6 @@
class ProjectServiceContainer extends \Symfony\Component\DependencyInjection\Tests\Fixtures\Container\ConstructorWithoutArgumentsContainer
{
private $parameters = [];
private $targetDirs = [];

public function __construct()
{
Expand Down
Expand Up @@ -20,7 +20,6 @@
class ProjectServiceContainer extends \Symfony\Component\DependencyInjection\Tests\Fixtures\Container\ConstructorWithMandatoryArgumentsContainer
{
private $parameters = [];
private $targetDirs = [];

public function __construct()
{
Expand Down
Expand Up @@ -20,7 +20,6 @@
class ProjectServiceContainer extends \Symfony\Component\DependencyInjection\Tests\Fixtures\Container\ConstructorWithOptionalArgumentsContainer
{
private $parameters = [];
private $targetDirs = [];

public function __construct()
{
Expand Down
Expand Up @@ -20,7 +20,6 @@
class ProjectServiceContainer extends \Symfony\Component\DependencyInjection\Tests\Fixtures\Container\NoConstructorContainer
{
private $parameters = [];
private $targetDirs = [];

public function __construct()
{
Expand Down
Expand Up @@ -20,7 +20,6 @@
class Container extends \Symfony\Component\DependencyInjection\Dump\AbstractContainer
{
private $parameters = [];
private $targetDirs = [];

public function __construct()
{
Expand Down
Expand Up @@ -18,7 +18,6 @@
class ProjectServiceContainer extends Container
{
private $parameters = [];
private $targetDirs = [];

public function __construct()
{
Expand Down
Expand Up @@ -18,7 +18,6 @@
class ProjectServiceContainer extends Container
{
private $parameters = [];
private $targetDirs = [];

public function __construct()
{
Expand Down
Expand Up @@ -18,14 +18,9 @@
class ProjectServiceContainer extends Container
{
private $parameters = [];
private $targetDirs = [];

public function __construct()
{
$dir = __DIR__;
for ($i = 1; $i <= 5; ++$i) {
$this->targetDirs[$i] = $dir = \dirname($dir);
}
$this->parameters = $this->getDefaultParameters();

$this->services = $this->privates = [];
Expand Down Expand Up @@ -61,7 +56,7 @@ public function getRemovedIds(): array
*/
protected function getTestService()
{
return $this->services['test'] = new \stdClass(('wiz'.$this->targetDirs[1]), [('wiz'.$this->targetDirs[1]) => ($this->targetDirs[2].'/')]);
return $this->services['test'] = new \stdClass(('wiz'.\dirname(__DIR__, 1)), [('wiz'.\dirname(__DIR__, 1)) => (\dirname(__DIR__, 2).'/')]);
}

public function getParameter($name)
Expand Down Expand Up @@ -103,29 +98,21 @@ public function getParameterBag(): ParameterBagInterface
return $this->parameterBag;
}

private $loadedDynamicParameters = [
'foo' => false,
'buz' => false,
];
private $loadedDynamicParameters = [];
private $dynamicParameters = [];

private function getDynamicParameter(string $name)
{
switch ($name) {
case 'foo': $value = ('wiz'.$this->targetDirs[1]); break;
case 'buz': $value = $this->targetDirs[2]; break;
default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name));
}
$this->loadedDynamicParameters[$name] = true;

return $this->dynamicParameters[$name] = $value;
throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name));
}

protected function getDefaultParameters(): array
{
return [
'foo' => ('wiz'.\dirname(__DIR__, 1)),
'bar' => __DIR__,
'baz' => (__DIR__.'/PhpDumperTest.php'),
'buz' => \dirname(__DIR__, 2),
];
}
}
Expand Up @@ -18,7 +18,6 @@
class ProjectServiceContainer extends Container
{
private $parameters = [];
private $targetDirs = [];

public function __construct()
{
Expand Down
Expand Up @@ -18,7 +18,6 @@
class ProjectServiceContainer extends Container
{
private $parameters = [];
private $targetDirs = [];

public function __construct()
{
Expand Down
Expand Up @@ -18,7 +18,6 @@
class ProjectServiceContainer extends Container
{
private $parameters = [];
private $targetDirs = [];

public function __construct()
{
Expand Down
Expand Up @@ -18,14 +18,9 @@
class Symfony_DI_PhpDumper_Test_EnvParameters extends Container
{
private $parameters = [];
private $targetDirs = [];

public function __construct()
{
$dir = __DIR__;
for ($i = 1; $i <= 5; ++$i) {
$this->targetDirs[$i] = $dir = \dirname($dir);
}
$this->parameters = $this->getDefaultParameters();

$this->services = $this->privates = [];
Expand Down Expand Up @@ -119,7 +114,6 @@ public function getParameterBag(): ParameterBagInterface
'baz' => false,
'json' => false,
'db_dsn' => false,
'env(json_file)' => false,
];
private $dynamicParameters = [];

Expand All @@ -130,7 +124,6 @@ private function getDynamicParameter(string $name)
case 'baz': $value = $this->getEnv('int:Baz'); break;
case 'json': $value = $this->getEnv('json:file:json_file'); break;
case 'db_dsn': $value = $this->getEnv('resolve:DB'); break;
case 'env(json_file)': $value = ($this->targetDirs[1].'/array.json'); break;
default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name));
}
$this->loadedDynamicParameters[$name] = true;
Expand All @@ -144,6 +137,7 @@ protected function getDefaultParameters(): array
'project_dir' => '/foo/bar',
'env(FOO)' => 'foo',
'env(DB)' => 'sqlite://%project_dir%/var/data.db',
'env(json_file)' => (\dirname(__DIR__, 1).'/array.json'),
];
}
}
Expand Up @@ -18,7 +18,6 @@
class ProjectServiceContainer extends Container
{
private $parameters = [];
private $targetDirs = [];

public function __construct()
{
Expand Down
Expand Up @@ -18,7 +18,6 @@
class ProjectServiceContainer extends Container
{
private $parameters = [];
private $targetDirs = [];

public function __construct()
{
Expand Down

0 comments on commit 541f80c

Please sign in to comment.