Skip to content

Instantly share code, notes, and snippets.

@makasim
Last active May 20, 2019 14:14
Show Gist options
  • Save makasim/19231f38b4e19b958d4f32cd1c3cc586 to your computer and use it in GitHub Desktop.
Save makasim/19231f38b4e19b958d4f32cd1c3cc586 to your computer and use it in GitHub Desktop.
<?php declare(strict_types=1);
namespace App\Infra\Symfony;
use Symfony\Component\DependencyInjection\EnvVarProcessorInterface;
use Symfony\Component\DependencyInjection\Exception\EnvNotFoundException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
class FileOrContentEnvVarProcessor implements EnvVarProcessorInterface
{
public function getEnv($prefix, $name, \Closure $getEnv)
{
if (0 !== substr_compare($name, '_FILE', -strlen('_FILE'))) {
throw new \LogicException(sprintf('The env var must end with _FILE. Got %s', $name));
}
try {
$file = $getEnv($name);
} catch (EnvNotFoundException $originalException) {
$orName = substr($name, 0, -strlen('_FILE'));
try {
return $getEnv($orName);
} catch (EnvNotFoundException $e) {
throw new EnvNotFoundException(sprintf('Environment variable not found: "%s" nor "%s".', $name, $orName), null, $originalException);
}
}
if (!is_scalar($file)) {
throw new RuntimeException(sprintf('Invalid file name: env var "%s" is non-scalar.', $name));
}
if (!file_exists($file)) {
throw new EnvNotFoundException(sprintf('File "%s" not found (resolved from "%s").', $file, $name));
}
return file_get_contents($file);
}
public static function getProvidedTypes()
{
return [
'fileor' => 'string',
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment