Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types=1);
- namespace App\Infrastructure\Env;
- use Symfony\Component\DependencyInjection\EnvVarProcessorInterface;
- final class ExplodeEnvVarProcessor implements EnvVarProcessorInterface
- {
- /**
- * @var array<string, string>
- */
- private const NAME_DELIMITER_MAP = [
- 'explode' => ',',
- 'dot' => '.',
- 'comma' => ',',
- 'colon' => ':',
- 'dash' => '-',
- 'bar' => '|',
- ];
- private const DEFAULT_CASTER = 'string';
- public function getEnv(string $prefix, string $name, \Closure $getEnv): array
- {
- $processors = explode(':', $name);
- $env = $getEnv(array_pop($processors));
- $caster = self::casts(self::DEFAULT_CASTER);
- if (2 === count($processors)) {
- $casterType = array_pop($processors); // int, string, float
- $caster = self::casts($casterType);
- $prefix = array_pop($processors); // comma, dot, dash, etc.
- }
- return array_map($caster, explode(self::NAME_DELIMITER_MAP[$prefix], $env));
- }
- public static function getProvidedTypes(): array
- {
- return [
- 'explode' => 'string',
- 'comma' => 'string',
- 'dot' => 'string',
- 'colon' => 'string',
- 'dash' => 'string',
- 'bar' => 'string',
- 'string' => 'int|string',
- 'integer' => 'int|string',
- ];
- }
- /**
- * @psalm-param 'string'|'int'|'float' $castTo
- *
- * @return callable(string): (string|int|float)
- */
- private static function casts(string $castTo): callable
- {
- $defaultCaster = fn (string $value): string => $value;
- return [
- 'string' => $defaultCaster,
- 'integer' => fn (string $value): int => (int) $value,
- 'float' => fn (string $value): float => (float) $value,
- ][$castTo] ?? $defaultCaster;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment