bug #41795 [FrameworkBundle] Replace var_export with VarExporter to use array short syntax in secrets list files (alexandre-daubois)

This PR was merged into the 4.4 branch.

Discussion
----------

[FrameworkBundle] Replace var_export with VarExporter to use array short syntax in secrets list files

| Q             | A
| ------------- | ---
| Branch?       | 4.4
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       | _N/A_
| License       | MIT
| Doc PR        | _N/A_

I've been using secrets a lot lately. Unfortunately, command exports the `{env}.list.php` with the "old" array syntax using `array()`, and writing `null` in uppercase.

This results in tedious situations with PHP CS Fixer (for example) rewriting the whole file to restore the modern syntax, each time we add a secret.

The Sodium vault currently uses `var_export`. I suggest using Symfony VarExporter, which does the work just fine. It adds a dependency to the FrameworkBundle, but it is a cleaner way to do it rather than using [this type of hack](https://www.php.net/manual/fr/function.var-export.php#124194) IMO.

Commits
-------

7f1c76212f [FrameworkBundle] Replace var_export with VarExporter to use array short syntax
This commit is contained in:
Alexander M. Turek 2021-06-22 22:03:29 +02:00
commit 124ecf07d0
1 changed files with 3 additions and 2 deletions

View File

@ -12,6 +12,7 @@
namespace Symfony\Bundle\FrameworkBundle\Secrets;
use Symfony\Component\DependencyInjection\EnvVarLoaderInterface;
use Symfony\Component\VarExporter\VarExporter;
/**
* @author Tobias Schultze <http://tobion.de>
@ -89,7 +90,7 @@ class SodiumVault extends AbstractVault implements EnvVarLoaderInterface
$list = $this->list();
$list[$name] = null;
uksort($list, 'strnatcmp');
file_put_contents($this->pathPrefix.'list.php', sprintf("<?php\n\nreturn %s;\n", var_export($list, true), \LOCK_EX));
file_put_contents($this->pathPrefix.'list.php', sprintf("<?php\n\nreturn %s;\n", VarExporter::export($list), \LOCK_EX));
$this->lastMessage = sprintf('Secret "%s" encrypted in "%s"; you can commit it.', $name, $this->getPrettyPath(\dirname($this->pathPrefix).\DIRECTORY_SEPARATOR));
}
@ -141,7 +142,7 @@ class SodiumVault extends AbstractVault implements EnvVarLoaderInterface
$list = $this->list();
unset($list[$name]);
file_put_contents($this->pathPrefix.'list.php', sprintf("<?php\n\nreturn %s;\n", var_export($list, true), \LOCK_EX));
file_put_contents($this->pathPrefix.'list.php', sprintf("<?php\n\nreturn %s;\n", VarExporter::export($list), \LOCK_EX));
$this->lastMessage = sprintf('Secret "%s" removed from "%s".', $name, $this->getPrettyPath(\dirname($this->pathPrefix).\DIRECTORY_SEPARATOR));