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

Skip to content

[Filesystem] Add the readFile() method #54173

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 17, 2024
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
2 changes: 1 addition & 1 deletion link
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ $directories = array_merge(...array_values(array_map(function ($part) {
$directories[] = __DIR__.'/src/Symfony/Contracts';
foreach ($directories as $dir) {
if ($filesystem->exists($composer = "$dir/composer.json")) {
$sfPackages[json_decode(file_get_contents($composer))->name] = $dir;
$sfPackages[json_decode($filesystem->readFile($composer), flags: JSON_THROW_ON_ERROR)->name] = $dir;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ private function getPublicDirectory(ContainerInterface $container): string
return $defaultPublicDir;
}

$composerConfig = json_decode(file_get_contents($composerFilePath), true);
$composerConfig = json_decode($this->filesystem->readFile($composerFilePath), true, flags: \JSON_THROW_ON_ERROR);

return $composerConfig['extra']['public-dir'] ?? $defaultPublicDir;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ private function warmup(string $warmupDir, string $realBuildDir): void
$search = [$warmupDir, str_replace('\\', '\\\\', $warmupDir)];
$replace = str_replace('\\', '/', $realBuildDir);
foreach (Finder::create()->files()->in($warmupDir) as $file) {
$content = str_replace($search, $replace, file_get_contents($file), $count);
$content = str_replace($search, $replace, $this->filesystem->readFile($file), $count);
if ($count) {
file_put_contents($file, $content);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\Glob;
use Symfony\Component\Form\Extension\HtmlSanitizer\Type\TextTypeHtmlSanitizerExtension;
Expand Down Expand Up @@ -3141,7 +3142,7 @@ private function getPublicDirectory(ContainerBuilder $container): string
}

$container->addResource(new FileResource($composerFilePath));
$composerConfig = json_decode(file_get_contents($composerFilePath), true);
$composerConfig = json_decode((new Filesystem())->readFile($composerFilePath), true, flags: \JSON_THROW_ON_ERROR);

return isset($composerConfig['extra']['public-dir']) ? $projectDir.'/'.$composerConfig['extra']['public-dir'] : $defaultPublicDir;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ function () use ($file) {
$kernelRef = new \ReflectionObject($this->kernel);
$kernelFile = $kernelRef->getFileName();
/** @var ResourceInterface[] $meta */
$meta = unserialize(file_get_contents($containerMetaFile));
$meta = unserialize($this->fs->readFile($containerMetaFile));
$found = false;
foreach ($meta as $resource) {
if ((string) $resource === $kernelFile) {
Expand All @@ -93,7 +93,7 @@ function () use ($file) {
);
$this->assertMatchesRegularExpression(
sprintf('/\'kernel.container_class\'\s*=>\s*\'%s\'/', $containerClass),
file_get_contents($containerFile),
$this->fs->readFile($containerFile),
'kernel.container_class is properly set on the dumped container'
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,18 @@
class SodiumVaultTest extends TestCase
{
private string $secretsDir;
private Filesystem $filesystem;

protected function setUp(): void
{
$this->filesystem = new Filesystem();
$this->secretsDir = sys_get_temp_dir().'/sf_secrets/test/';
(new Filesystem())->remove($this->secretsDir);
$this->filesystem->remove($this->secretsDir);
}

protected function tearDown(): void
{
(new Filesystem())->remove($this->secretsDir);
$this->filesystem->remove($this->secretsDir);
}

public function testGenerateKeys()
Expand All @@ -41,8 +43,8 @@ public function testGenerateKeys()
$this->assertFileExists($this->secretsDir.'/test.encrypt.public.php');
$this->assertFileExists($this->secretsDir.'/test.decrypt.private.php');

$encKey = file_get_contents($this->secretsDir.'/test.encrypt.public.php');
$decKey = file_get_contents($this->secretsDir.'/test.decrypt.private.php');
$encKey = $this->filesystem->readFile($this->secretsDir.'/test.encrypt.public.php');
$decKey = $this->filesystem->readFile($this->secretsDir.'/test.decrypt.private.php');

$this->assertFalse($vault->generateKeys());
$this->assertStringEqualsFile($this->secretsDir.'/test.encrypt.public.php', $encKey);
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"symfony/http-foundation": "^6.4|^7.0",
"symfony/http-kernel": "^6.4|^7.0",
"symfony/polyfill-mbstring": "~1.0",
"symfony/filesystem": "^6.4|^7.0",
"symfony/filesystem": "^7.1",
"symfony/finder": "^6.4|^7.0",
"symfony/routing": "^6.4|^7.0"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,20 @@

namespace Symfony\Component\AssetMapper;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Path;

/**
* Reads and writes compiled configuration files for asset mapper.
*/
class CompiledAssetMapperConfigReader
{
public function __construct(private readonly string $directory)
{
private readonly Filesystem $filesystem;

public function __construct(
private readonly string $directory,
) {
$this->filesystem = new Filesystem();
}

public function configExists(string $filename): bool
Expand All @@ -29,7 +34,7 @@ public function configExists(string $filename): bool

public function loadConfig(string $filename): array
{
return json_decode(file_get_contents(Path::join($this->directory, $filename)), true, 512, \JSON_THROW_ON_ERROR);
return json_decode($this->filesystem->readFile(Path::join($this->directory, $filename)), true, 512, \JSON_THROW_ON_ERROR);
}

public function saveConfig(string $filename, array $data): string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\Component\Config\Resource\FileExistenceResource;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Config\Resource\ResourceInterface;
use Symfony\Component\Filesystem\Filesystem;

/**
* Decorates the asset factory to load MappedAssets from cache when possible.
Expand All @@ -36,7 +37,7 @@ public function createMappedAsset(string $logicalPath, string $sourcePath): ?Map
$configCache = new ConfigCache($cachePath, $this->debug);

if ($configCache->isFresh()) {
return unserialize(file_get_contents($cachePath));
return unserialize((new Filesystem())->readFile($cachePath));
}

$mappedAsset = $this->innerFactory->createMappedAsset($logicalPath, $sourcePath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Symfony\Component\AssetMapper\Exception\RuntimeException;
use Symfony\Component\AssetMapper\MappedAsset;
use Symfony\Component\AssetMapper\Path\PublicAssetsPathResolverInterface;
use Symfony\Component\Filesystem\Filesystem;

/**
* Creates MappedAsset objects by reading their contents & passing it through compilers.
Expand Down Expand Up @@ -104,7 +105,7 @@ private function compileContent(MappedAsset $asset): ?string
return null;
}

$content = file_get_contents($asset->sourcePath);
$content = (new Filesystem())->readFile($asset->sourcePath);
$compiled = $this->compiler->compile($content, $asset);

return $compiled !== $content ? $compiled : null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,9 @@ public function testAssetsAreCompiled()
$this->filesystem->remove($targetBuildDir);
}
// put old "built" versions to make sure the system skips using these
$this->filesystem->mkdir($targetBuildDir);
file_put_contents($targetBuildDir.'/manifest.json', '{}');
file_put_contents($targetBuildDir.'/importmap.json', '{}');
file_put_contents($targetBuildDir.'/entrypoint.file6.json', '[]');
$this->filesystem->dumpFile($targetBuildDir.'/manifest.json', '{}');
$this->filesystem->dumpFile($targetBuildDir.'/importmap.json', '{}');
$this->filesystem->dumpFile($targetBuildDir.'/entrypoint.file6.json', '[]');

$command = $application->find('asset-map:compile');
$tester = new CommandTester($command);
Expand All @@ -65,7 +64,7 @@ public function testAssetsAreCompiled()
import '../file4.js';
console.log('file5.js');

EOF, file_get_contents($targetBuildDir.'/subdir/file5-f4fdc37375c7f5f2629c5659a0579967.js'));
EOF, $this->filesystem->readFile($targetBuildDir.'/subdir/file5-f4fdc37375c7f5f2629c5659a0579967.js'));

$finder = new Finder();
$finder->in($targetBuildDir)->files();
Expand All @@ -83,10 +82,10 @@ public function testAssetsAreCompiled()
'vendor/@hotwired/stimulus/stimulus.index.js',
'vendor/lodash/lodash.index.js',
'voilà.css',
], array_keys(json_decode(file_get_contents($targetBuildDir.'/manifest.json'), true)));
], array_keys(json_decode($this->filesystem->readFile($targetBuildDir.'/manifest.json'), true)));

$this->assertFileExists($targetBuildDir.'/importmap.json');
$actualImportMap = json_decode(file_get_contents($targetBuildDir.'/importmap.json'), true);
$actualImportMap = json_decode($this->filesystem->readFile($targetBuildDir.'/importmap.json'), true);
$this->assertSame([
'@hotwired/stimulus', // in importmap
'lodash', // in importmap
Expand All @@ -102,7 +101,7 @@ public function testAssetsAreCompiled()
$this->assertSame('js', $actualImportMap['@hotwired/stimulus']['type']);

$this->assertFileExists($targetBuildDir.'/entrypoint.file6.json');
$entrypointData = json_decode(file_get_contents($targetBuildDir.'/entrypoint.file6.json'), true);
$entrypointData = json_decode($this->filesystem->readFile($targetBuildDir.'/entrypoint.file6.json'), true);
$this->assertSame([
'/assets/subdir/file5.js',
'/assets/file4.js',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public function testSaveConfig()
{
$reader = new CompiledAssetMapperConfigReader($this->writableRoot);
$this->assertEquals($this->writableRoot.\DIRECTORY_SEPARATOR.'foo.json', realpath($reader->saveConfig('foo.json', ['foo' => 'bar'])));
$this->assertEquals(['foo' => 'bar'], json_decode(file_get_contents($this->writableRoot.'/foo.json'), true));
$this->assertEquals(['foo' => 'bar'], json_decode($this->filesystem->readFile($this->writableRoot.'/foo.json'), true));
}

public function testRemoveConfig()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ private function loadConfigCacheMetadataFor(MappedAsset $mappedAsset): array
{
$cachedPath = $this->getConfigCachePath($mappedAsset).'.meta';

return unserialize(file_get_contents($cachedPath));
return unserialize($this->filesystem->readFile($cachedPath));
}

private function saveConfigCache(MappedAsset $mappedAsset): void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,12 @@ public function testDownloadPackagesDownloadsEverythingWithNoInstalled()
$this->assertFileExists(self::$writableRoot.'/assets/vendor/foo/foo.index.js');
$this->assertFileExists(self::$writableRoot.'/assets/vendor/bar.js/file.js');
$this->assertFileExists(self::$writableRoot.'/assets/vendor/baz/baz.index.css');
$this->assertEquals('foo content', file_get_contents(self::$writableRoot.'/assets/vendor/foo/foo.index.js'));
$this->assertEquals('foo content', $this->filesystem->readFile(self::$writableRoot.'/assets/vendor/foo/foo.index.js'));
$this->assertFileExists(self::$writableRoot.'/assets/vendor/foo/path/to/extra-file.woff');
$this->assertEquals('extra file contents', file_get_contents(self::$writableRoot.'/assets/vendor/foo/path/to/extra-file.woff'));
$this->assertEquals('bar content', file_get_contents(self::$writableRoot.'/assets/vendor/bar.js/file.js'));
$this->assertEquals('baz content', file_get_contents(self::$writableRoot.'/assets/vendor/baz/baz.index.css'));
$this->assertEquals('different content', file_get_contents(self::$writableRoot.'/assets/vendor/custom_specifier/custom_specifier.index.js'));
$this->assertEquals('extra file contents', $this->filesystem->readFile(self::$writableRoot.'/assets/vendor/foo/path/to/extra-file.woff'));
$this->assertEquals('bar content', $this->filesystem->readFile(self::$writableRoot.'/assets/vendor/bar.js/file.js'));
$this->assertEquals('baz content', $this->filesystem->readFile(self::$writableRoot.'/assets/vendor/baz/baz.index.css'));
$this->assertEquals('different content', $this->filesystem->readFile(self::$writableRoot.'/assets/vendor/custom_specifier/custom_specifier.index.js'));

$installed = require self::$writableRoot.'/assets/vendor/installed.php';
$this->assertEquals(
Expand Down Expand Up @@ -150,9 +150,9 @@ public function testPackagesWithCorrectInstalledVersionSkipped()
$this->assertFileExists(self::$writableRoot.'/assets/vendor/foo/foo.index.js');
$this->assertFileExists(self::$writableRoot.'/assets/vendor/bar.js/file.js');
$this->assertFileExists(self::$writableRoot.'/assets/vendor/baz/baz.index.css');
$this->assertEquals('original foo content', file_get_contents(self::$writableRoot.'/assets/vendor/foo/foo.index.js'));
$this->assertEquals('new bar content', file_get_contents(self::$writableRoot.'/assets/vendor/bar.js/file.js'));
$this->assertEquals('new baz content', file_get_contents(self::$writableRoot.'/assets/vendor/baz/baz.index.css'));
$this->assertEquals('original foo content', $this->filesystem->readFile(self::$writableRoot.'/assets/vendor/foo/foo.index.js'));
$this->assertEquals('new bar content', $this->filesystem->readFile(self::$writableRoot.'/assets/vendor/bar.js/file.js'));
$this->assertEquals('new baz content', $this->filesystem->readFile(self::$writableRoot.'/assets/vendor/baz/baz.index.css'));
$this->assertFileExists(self::$writableRoot.'/assets/vendor/has-missing-extra/has-missing-extra.index.js');

$installed = require self::$writableRoot.'/assets/vendor/installed.php';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public function testSave()
$storage->save($entry, 'any content');
$targetPath = self::$writableRoot.'/assets/vendor/module_specifier/module_specifier.index.js';
$this->assertFileExists($targetPath);
$this->assertEquals('any content', file_get_contents($targetPath));
$this->assertEquals('any content', $this->filesystem->readFile($targetPath));
}

public function testSaveExtraFile()
Expand All @@ -80,7 +80,7 @@ public function testSaveExtraFile()
$storage->saveExtraFile($entry, '/path/to/extra-file.woff2', 'any content');
$targetPath = self::$writableRoot.'/assets/vendor/module_specifier/path/to/extra-file.woff2';
$this->assertFileExists($targetPath);
$this->assertEquals('any content', file_get_contents($targetPath));
$this->assertEquals('any content', $this->filesystem->readFile($targetPath));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public function testWrite()
$filesystem = new LocalPublicAssetsFilesystem(self::$writableRoot);
$filesystem->write('foo/bar.js', 'foobar');
$this->assertFileExists(self::$writableRoot.'/foo/bar.js');
$this->assertSame('foobar', file_get_contents(self::$writableRoot.'/foo/bar.js'));
$this->assertSame('foobar', $this->filesystem->readFile(self::$writableRoot.'/foo/bar.js'));

// with a directory
$filesystem->write('foo/baz/bar.js', 'foobar');
Expand All @@ -50,6 +50,6 @@ public function testCopy()
$filesystem = new LocalPublicAssetsFilesystem(self::$writableRoot);
$filesystem->copy(__DIR__.'/../Fixtures/importmaps/assets/pizza/index.js', 'foo/bar.js');
$this->assertFileExists(self::$writableRoot.'/foo/bar.js');
$this->assertSame("console.log('pizza/index.js');", trim(file_get_contents(self::$writableRoot.'/foo/bar.js')));
$this->assertSame("console.log('pizza/index.js');", trim($this->filesystem->readFile(self::$writableRoot.'/foo/bar.js')));
}
}
2 changes: 1 addition & 1 deletion src/Symfony/Component/AssetMapper/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"php": ">=8.2",
"composer/semver": "^3.0",
"symfony/deprecation-contracts": "^2.1|^3",
"symfony/filesystem": "^6.4|^7.0",
"symfony/filesystem": "^7.1",
"symfony/http-client": "^6.4|^7.0"
},
"require-dev": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ public function write(string $content, ?array $metadata = null): void
private function safelyUnserialize(string $file): mixed
{
$meta = false;
$content = file_get_contents($file);
$content = (new Filesystem())->readFile($file);
$signalingException = new \UnexpectedValueException();
$prevUnserializeHandler = ini_set('unserialize_callback_func', self::class.'::handleUnserializeCallback');
$prevErrorHandler = set_error_handler(function ($type, $msg, $file, $line, $context = []) use (&$prevErrorHandler, $signalingException) {
Expand Down
5 changes: 3 additions & 2 deletions src/Symfony/Component/Config/Util/XmlUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\Config\Util\Exception\InvalidXmlException;
use Symfony\Component\Config\Util\Exception\XmlParsingException;
use Symfony\Component\Filesystem\Filesystem;

/**
* XMLUtils is a bunch of utility methods to XML operations.
Expand Down Expand Up @@ -79,7 +80,7 @@ public static function parse(string $content, string|callable|null $schemaOrCall
$valid = false;
}
} elseif (is_file($schemaOrCallable)) {
$schemaSource = file_get_contents((string) $schemaOrCallable);
$schemaSource = (new Filesystem())->readFile((string) $schemaOrCallable);
$valid = @$dom->schemaValidateSource($schemaSource);
} else {
libxml_use_internal_errors($internalErrors);
Expand Down Expand Up @@ -122,7 +123,7 @@ public static function loadFile(string $file, string|callable|null $schemaOrCall
throw new \InvalidArgumentException(sprintf('File "%s" is not readable.', $file));
}

$content = @file_get_contents($file);
$content = (new Filesystem())->readFile($file);

if ('' === trim($content)) {
throw new \InvalidArgumentException(sprintf('File "%s" does not contain valid XML, it is empty.', $file));
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Config/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"require": {
"php": ">=8.2",
"symfony/deprecation-contracts": "^2.5|^3",
"symfony/filesystem": "^6.4|^7.0",
"symfony/filesystem": "^7.1",
"symfony/polyfill-ctype": "~1.8"
},
"require-dev": {
Expand Down
Loading