Skip to content

Commit

Permalink
minor #36556 Use is_file() instead of file_exists() where possible (n…
Browse files Browse the repository at this point in the history
…icolas-grekas)

This PR was merged into the 5.1-dev branch.

Discussion
----------

Use is_file() instead of file_exists() where possible

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | no
| Deprecations? | no
| Tickets       | Fix #36493
| License       | MIT
| Doc PR        | -

Thanks to caching, `is_file()` is much faster than `file_exists()`.
I screened the codebase for places where it could matter, here they are.

Commits
-------

f38904e Use is_file() instead of file_exists() where possible
  • Loading branch information
fabpot committed Apr 24, 2020
2 parents 83b37e8 + f38904e commit 87c9ab4
Show file tree
Hide file tree
Showing 17 changed files with 45 additions and 45 deletions.
2 changes: 1 addition & 1 deletion src/Symfony/Bundle/FrameworkBundle/KernelBrowser.php
Expand Up @@ -198,7 +198,7 @@ protected function getScript($request)
if (0 === strpos($class, 'ComposerAutoloaderInit')) {
$r = new \ReflectionClass($class);
$file = \dirname($r->getFileName(), 2).'/autoload.php';
if (file_exists($file)) {
if (is_file($file)) {
$requires .= 'require_once '.var_export($file, true).";\n";
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Bundle/FrameworkBundle/Secrets/DotenvVault.php
Expand Up @@ -38,7 +38,7 @@ public function seal(string $name, string $value): void
$this->validateName($name);
$v = str_replace("'", "'\\''", $value);

$content = file_exists($this->dotenvFile) ? file_get_contents($this->dotenvFile) : '';
$content = is_file($this->dotenvFile) ? file_get_contents($this->dotenvFile) : '';
$content = preg_replace("/^$name=((\\\\'|'[^']++')++|.*)/m", "$name='$v'", $content, -1, $count);

if (!$count) {
Expand Down Expand Up @@ -70,7 +70,7 @@ public function remove(string $name): bool
$this->lastMessage = null;
$this->validateName($name);

$content = file_exists($this->dotenvFile) ? file_get_contents($this->dotenvFile) : '';
$content = is_file($this->dotenvFile) ? file_get_contents($this->dotenvFile) : '';
$content = preg_replace("/^$name=((\\\\'|'[^']++')++|.*)\n?/m", '', $content, -1, $count);

if ($count) {
Expand Down
12 changes: 6 additions & 6 deletions src/Symfony/Bundle/FrameworkBundle/Secrets/SodiumVault.php
Expand Up @@ -58,7 +58,7 @@ public function generateKeys(bool $override = false): bool
// ignore failures to load keys
}

if ('' !== $this->decryptionKey && !file_exists($this->pathPrefix.'encrypt.public.php')) {
if ('' !== $this->decryptionKey && !is_file($this->pathPrefix.'encrypt.public.php')) {
$this->export('encrypt.public', $this->encryptionKey);
}

Expand Down Expand Up @@ -99,7 +99,7 @@ public function reveal(string $name): ?string
$this->lastMessage = null;
$this->validateName($name);

if (!file_exists($file = $this->pathPrefix.$name.'.'.substr_replace(md5($name), '.php', -26))) {
if (!is_file($file = $this->pathPrefix.$name.'.'.substr_replace(md5($name), '.php', -26))) {
$this->lastMessage = sprintf('Secret "%s" not found in "%s".', $name, $this->getPrettyPath(\dirname($this->pathPrefix).\DIRECTORY_SEPARATOR));

return null;
Expand Down Expand Up @@ -133,7 +133,7 @@ public function remove(string $name): bool
$this->lastMessage = null;
$this->validateName($name);

if (!file_exists($file = $this->pathPrefix.$name.'.'.substr_replace(md5($name), '.php', -26))) {
if (!is_file($file = $this->pathPrefix.$name.'.'.substr_replace(md5($name), '.php', -26))) {
$this->lastMessage = sprintf('Secret "%s" not found in "%s".', $name, $this->getPrettyPath(\dirname($this->pathPrefix).\DIRECTORY_SEPARATOR));

return false;
Expand All @@ -152,7 +152,7 @@ public function list(bool $reveal = false): array
{
$this->lastMessage = null;

if (!file_exists($file = $this->pathPrefix.'list.php')) {
if (!is_file($file = $this->pathPrefix.'list.php')) {
return [];
}

Expand Down Expand Up @@ -184,11 +184,11 @@ private function loadKeys(): void
return;
}

if (file_exists($this->pathPrefix.'decrypt.private.php')) {
if (is_file($this->pathPrefix.'decrypt.private.php')) {
$this->decryptionKey = (string) include $this->pathPrefix.'decrypt.private.php';
}

if (file_exists($this->pathPrefix.'encrypt.public.php')) {
if (is_file($this->pathPrefix.'encrypt.public.php')) {
$this->encryptionKey = (string) include $this->pathPrefix.'encrypt.public.php';
} elseif ('' !== $this->decryptionKey) {
$this->encryptionKey = sodium_crypto_box_publickey($this->decryptionKey);
Expand Down
Expand Up @@ -53,7 +53,7 @@ public function applyVersion(string $path)
private function getManifestPath(string $path): ?string
{
if (null === $this->manifestData) {
if (!file_exists($this->manifestPath)) {
if (!is_file($this->manifestPath)) {
throw new \RuntimeException(sprintf('Asset manifest file "%s" does not exist.', $this->manifestPath));
}

Expand Down
Expand Up @@ -65,11 +65,11 @@ protected function doClear(string $namespace)
}

for ($i = 0; $i < 38; ++$i) {
if (!file_exists($dir.$chars[$i])) {
if (!is_dir($dir.$chars[$i])) {
continue;
}
for ($j = 0; $j < 38; ++$j) {
if (!file_exists($d = $dir.$chars[$i].\DIRECTORY_SEPARATOR.$chars[$j])) {
if (!is_dir($d = $dir.$chars[$i].\DIRECTORY_SEPARATOR.$chars[$j])) {
continue;
}
foreach (scandir($d, SCANDIR_SORT_NONE) ?: [] as $link) {
Expand Down Expand Up @@ -136,7 +136,7 @@ protected function doDeleteYieldTags(array $ids): iterable
{
foreach ($ids as $id) {
$file = $this->getFile($id);
if (!file_exists($file) || !$h = @fopen($file, 'rb')) {
if (!is_file($file) || !$h = @fopen($file, 'rb')) {
continue;
}

Expand Down Expand Up @@ -193,7 +193,7 @@ protected function doDeleteTagRelations(array $tagData): bool
protected function doInvalidate(array $tagIds): bool
{
foreach ($tagIds as $tagId) {
if (!file_exists($tagFolder = $this->getTagFolder($tagId))) {
if (!is_dir($tagFolder = $this->getTagFolder($tagId))) {
continue;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Cache/Adapter/PhpArrayAdapter.php
Expand Up @@ -390,7 +390,7 @@ private function initialize()
{
if (isset(self::$valuesCache[$this->file])) {
$values = self::$valuesCache[$this->file];
} elseif (!file_exists($this->file)) {
} elseif (!is_file($this->file)) {
$this->keys = $this->values = [];

return;
Expand Down
14 changes: 7 additions & 7 deletions src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php
Expand Up @@ -38,7 +38,7 @@ private function init(string $namespace, ?string $directory)
} else {
$directory .= \DIRECTORY_SEPARATOR.'@';
}
if (!file_exists($directory)) {
if (!is_dir($directory)) {
@mkdir($directory, 0777, true);
}
$directory .= \DIRECTORY_SEPARATOR;
Expand Down Expand Up @@ -77,7 +77,7 @@ protected function doDelete(array $ids)

foreach ($ids as $id) {
$file = $this->getFile($id);
$ok = (!file_exists($file) || $this->doUnlink($file) || !file_exists($file)) && $ok;
$ok = (!is_file($file) || $this->doUnlink($file) || !file_exists($file)) && $ok;
}

return $ok;
Expand Down Expand Up @@ -113,7 +113,7 @@ private function getFile(string $id, bool $mkdir = false, string $directory = nu
$hash = str_replace('/', '-', base64_encode(hash('md5', static::class.$id, true)));
$dir = ($directory ?? $this->directory).strtoupper($hash[0].\DIRECTORY_SEPARATOR.$hash[1].\DIRECTORY_SEPARATOR);

if ($mkdir && !file_exists($dir)) {
if ($mkdir && !is_dir($dir)) {
@mkdir($dir, 0777, true);
}

Expand All @@ -127,19 +127,19 @@ private function getFileKey(string $file): string

private function scanHashDir(string $directory): \Generator
{
if (!file_exists($directory)) {
if (!is_dir($directory)) {
return;
}

$chars = '+-ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

for ($i = 0; $i < 38; ++$i) {
if (!file_exists($directory.$chars[$i])) {
if (!is_dir($directory.$chars[$i])) {
continue;
}

for ($j = 0; $j < 38; ++$j) {
if (!file_exists($dir = $directory.$chars[$i].\DIRECTORY_SEPARATOR.$chars[$j])) {
if (!is_dir($dir = $directory.$chars[$i].\DIRECTORY_SEPARATOR.$chars[$j])) {
continue;
}

Expand Down Expand Up @@ -178,7 +178,7 @@ public function __destruct()
if (method_exists(parent::class, '__destruct')) {
parent::__destruct();
}
if (null !== $this->tmp && file_exists($this->tmp)) {
if (null !== $this->tmp && is_file($this->tmp)) {
unlink($this->tmp);
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/Cache/Traits/FilesystemTrait.php
Expand Up @@ -59,7 +59,7 @@ protected function doFetch(array $ids)

foreach ($ids as $id) {
$file = $this->getFile($id);
if (!file_exists($file) || !$h = @fopen($file, 'rb')) {
if (!is_file($file) || !$h = @fopen($file, 'rb')) {
continue;
}
if (($expiresAt = (int) fgets($h)) && $now >= $expiresAt) {
Expand All @@ -85,7 +85,7 @@ protected function doHave(string $id)
{
$file = $this->getFile($id);

return file_exists($file) && (@filemtime($file) > time() || $this->doFetch([$id]));
return is_file($file) && (@filemtime($file) > time() || $this->doFetch([$id]));
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Config/Resource/ComposerResource.php
Expand Up @@ -61,7 +61,7 @@ private static function refresh()
if ('C' === $class[0] && 0 === strpos($class, 'ComposerAutoloaderInit')) {
$r = new \ReflectionClass($class);
$v = \dirname($r->getFileName(), 2);
if (file_exists($v.'/composer/installed.json')) {
if (is_file($v.'/composer/installed.json')) {
self::$runtimeVendors[$v] = @filemtime($v.'/composer/installed.json');
}
}
Expand Down
Expand Up @@ -83,7 +83,7 @@ private function loadFiles(\ReflectionClass $class)
}
do {
$file = $class->getFileName();
if (false !== $file && file_exists($file)) {
if (false !== $file && is_file($file)) {
foreach ($this->excludedVendors as $vendor) {
if (0 === strpos($file, $vendor) && false !== strpbrk(substr($file, \strlen($vendor), 1), '/'.\DIRECTORY_SEPARATOR)) {
$file = false;
Expand Down
Expand Up @@ -114,7 +114,7 @@ public function getEnv(string $prefix, string $name, \Closure $getEnv)
if (!is_scalar($file = $getEnv($name))) {
throw new RuntimeException(sprintf('Invalid file name: env var "%s" is non-scalar.', $name));
}
if (!file_exists($file)) {
if (!is_file($file)) {
throw new EnvNotFoundException(sprintf('File "%s" not found (resolved from "%s").', $file, $name));
}

Expand Down
Expand Up @@ -670,7 +670,7 @@ protected function loadFile($file)
throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file));
}

if (!file_exists($file)) {
if (!is_file($file)) {
throw new InvalidArgumentException(sprintf('The file "%s" does not exist.', $file));
}

Expand Down
10 changes: 5 additions & 5 deletions src/Symfony/Component/Dotenv/Dotenv.php
Expand Up @@ -110,7 +110,7 @@ public function loadEnv(string $path, string $envKey = null, string $defaultEnv
{
$k = $envKey ?? $this->envKey;

if (file_exists($path) || !file_exists($p = "$path.dist")) {
if (is_file($path) || !is_file($p = "$path.dist")) {
$this->load($path);
} else {
$this->load($p);
Expand All @@ -120,7 +120,7 @@ public function loadEnv(string $path, string $envKey = null, string $defaultEnv
$this->populate([$k => $env = $defaultEnv]);
}

if (!\in_array($env, $testEnvs, true) && file_exists($p = "$path.local")) {
if (!\in_array($env, $testEnvs, true) && is_file($p = "$path.local")) {
$this->load($p);
$env = $_SERVER[$k] ?? $_ENV[$k] ?? $env;
}
Expand All @@ -129,11 +129,11 @@ public function loadEnv(string $path, string $envKey = null, string $defaultEnv
return;
}

if (file_exists($p = "$path.$env")) {
if (is_file($p = "$path.$env")) {
$this->load($p);
}

if (file_exists($p = "$path.$env.local")) {
if (is_file($p = "$path.$env.local")) {
$this->load($p);
}
}
Expand All @@ -148,7 +148,7 @@ public function loadEnv(string $path, string $envKey = null, string $defaultEnv
public function bootEnv(string $path, string $defaultEnv = 'dev', array $testEnvs = ['test']): void
{
$p = $path.'.local.php';
$env = (\function_exists('opcache_is_script_cached') && @opcache_is_script_cached($p)) || file_exists($p) ? include $p : null;
$env = is_file($p) ? include $p : null;
$k = $this->envKey;

if (\is_array($env) && (!isset($env[$k]) || ($_SERVER[$k] ?? $_ENV[$k] ?? $env[$k]) === $env[$k])) {
Expand Down
8 changes: 4 additions & 4 deletions src/Symfony/Component/ErrorHandler/DebugClassLoader.php
Expand Up @@ -185,7 +185,7 @@ public function __construct(callable $classLoader)
];

if (!isset(self::$caseCheck)) {
$file = file_exists(__FILE__) ? __FILE__ : rtrim(realpath('.'), \DIRECTORY_SEPARATOR);
$file = is_file(__FILE__) ? __FILE__ : rtrim(realpath('.'), \DIRECTORY_SEPARATOR);
$i = strrpos($file, \DIRECTORY_SEPARATOR);
$dir = substr($file, 0, 1 + $i);
$file = substr($file, 1 + $i);
Expand Down Expand Up @@ -904,7 +904,7 @@ private function patchMethod(\ReflectionMethod $method, string $returnType, stri
static $patchedMethods = [];
static $useStatements = [];

if (!file_exists($file = $method->getFileName()) || isset($patchedMethods[$file][$startLine = $method->getStartLine()])) {
if (!is_file($file = $method->getFileName()) || isset($patchedMethods[$file][$startLine = $method->getStartLine()])) {
return;
}

Expand Down Expand Up @@ -1002,7 +1002,7 @@ private static function getUseStatements(string $file): array
$useMap = [];
$useOffset = 0;

if (!file_exists($file)) {
if (!is_file($file)) {
return [$namespace, $useOffset, $useMap];
}

Expand Down Expand Up @@ -1045,7 +1045,7 @@ private function fixReturnStatements(\ReflectionMethod $method, string $returnTy
return;
}

if (!file_exists($file = $method->getFileName())) {
if (!is_file($file = $method->getFileName())) {
return;
}

Expand Down
6 changes: 3 additions & 3 deletions src/Symfony/Component/HttpKernel/Kernel.php
Expand Up @@ -280,12 +280,12 @@ public function getProjectDir()
if (null === $this->projectDir) {
$r = new \ReflectionObject($this);

if (!file_exists($dir = $r->getFileName())) {
if (!is_file($dir = $r->getFileName())) {
throw new \LogicException(sprintf('Cannot auto-detect project dir for kernel of class "%s".', $r->name));
}

$dir = $rootDir = \dirname($dir);
while (!file_exists($dir.'/composer.json')) {
while (!is_file($dir.'/composer.json')) {
if ($dir === \dirname($dir)) {
return $this->projectDir = $rootDir;
}
Expand Down Expand Up @@ -432,7 +432,7 @@ protected function initializeContainer()
$errorLevel = error_reporting(E_ALL ^ E_WARNING);

try {
if (file_exists($cachePath) && \is_object($this->container = include $cachePath)
if (is_file($cachePath) && \is_object($this->container = include $cachePath)
&& (!$this->debug || (self::$freshCache[$cachePath] ?? $cache->isFresh()))
) {
self::$freshCache[$cachePath] = true;
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/VarDumper/Caster/ExceptionCaster.php
Expand Up @@ -212,15 +212,15 @@ public static function castFrameStub(FrameStub $frame, array $a, Stub $stub, boo
$ellipsisTail = isset($ellipsis->attr['ellipsis-tail']) ? $ellipsis->attr['ellipsis-tail'] : 0;
$ellipsis = isset($ellipsis->attr['ellipsis']) ? $ellipsis->attr['ellipsis'] : 0;

if (file_exists($f['file']) && 0 <= self::$srcContext) {
if (is_file($f['file']) && 0 <= self::$srcContext) {
if (!empty($f['class']) && (is_subclass_of($f['class'], 'Twig\Template') || is_subclass_of($f['class'], 'Twig_Template')) && method_exists($f['class'], 'getDebugInfo')) {
$template = isset($f['object']) ? $f['object'] : unserialize(sprintf('O:%d:"%s":0:{}', \strlen($f['class']), $f['class']));

$ellipsis = 0;
$templateSrc = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getCode() : (method_exists($template, 'getSource') ? $template->getSource() : '');
$templateInfo = $template->getDebugInfo();
if (isset($templateInfo[$f['line']])) {
if (!method_exists($template, 'getSourceContext') || !file_exists($templatePath = $template->getSourceContext()->getPath())) {
if (!method_exists($template, 'getSourceContext') || !is_file($templatePath = $template->getSourceContext()->getPath())) {
$templatePath = null;
}
if ($templateSrc) {
Expand Down
6 changes: 3 additions & 3 deletions src/Symfony/Component/VarDumper/Caster/LinkStub.php
Expand Up @@ -43,7 +43,7 @@ public function __construct($label, int $line = 0, $href = null)

return;
}
if (!file_exists($href)) {
if (!is_file($href)) {
return;
}
if ($line) {
Expand Down Expand Up @@ -72,7 +72,7 @@ private function getComposerRoot(string $file, bool &$inVendor)
if ('C' === $class[0] && 0 === strpos($class, 'ComposerAutoloaderInit')) {
$r = new \ReflectionClass($class);
$v = \dirname($r->getFileName(), 2);
if (file_exists($v.'/composer/installed.json')) {
if (is_file($v.'/composer/installed.json')) {
self::$vendorRoots[] = $v.\DIRECTORY_SEPARATOR;
}
}
Expand All @@ -91,7 +91,7 @@ private function getComposerRoot(string $file, bool &$inVendor)
}

$parent = $dir;
while (!@file_exists($parent.'/composer.json')) {
while (!@is_file($parent.'/composer.json')) {
if (!@file_exists($parent)) {
// open_basedir restriction in effect
break;
Expand Down

0 comments on commit 87c9ab4

Please sign in to comment.