Guest User

Untitled

a guest
Jul 12th, 2021
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.95 KB | None | 0 0
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Infrastructure\Env;
  6.  
  7. use Symfony\Component\DependencyInjection\EnvVarProcessorInterface;
  8.  
  9. final class ExplodeEnvVarProcessor implements EnvVarProcessorInterface
  10. {
  11.     /**
  12.      * @var array<string, string>
  13.      */
  14.     private const NAME_DELIMITER_MAP = [
  15.         'explode' => ',',
  16.         'dot' => '.',
  17.         'comma' => ',',
  18.         'colon' => ':',
  19.         'dash' => '-',
  20.         'bar' => '|',
  21.     ];
  22.  
  23.     private const DEFAULT_CASTER = 'string';
  24.  
  25.     public function getEnv(string $prefix, string $name, \Closure $getEnv): array
  26.     {
  27.         $processors = explode(':', $name);
  28.  
  29.         $env = $getEnv(array_pop($processors));
  30.  
  31.         $caster = self::casts(self::DEFAULT_CASTER);
  32.  
  33.         if (2 === count($processors)) {
  34.             $casterType = array_pop($processors); // int, string, float
  35.  
  36.             $caster = self::casts($casterType);
  37.  
  38.             $prefix = array_pop($processors); // comma, dot, dash, etc.
  39.         }
  40.  
  41.         return array_map($caster, explode(self::NAME_DELIMITER_MAP[$prefix], $env));
  42.     }
  43.  
  44.     public static function getProvidedTypes(): array
  45.     {
  46.         return [
  47.             'explode' => 'string',
  48.             'comma' => 'string',
  49.             'dot' => 'string',
  50.             'colon' => 'string',
  51.             'dash' => 'string',
  52.             'bar' => 'string',
  53.             'string' => 'int|string',
  54.             'integer' => 'int|string',
  55.         ];
  56.     }
  57.  
  58.     /**
  59.      * @psalm-param 'string'|'int'|'float' $castTo
  60.      *
  61.      * @return callable(string): (string|int|float)
  62.      */
  63.     private static function casts(string $castTo): callable
  64.     {
  65.         $defaultCaster = fn (string $value): string => $value;
  66.  
  67.         return [
  68.             'string' => $defaultCaster,
  69.             'integer' => fn (string $value): int => (int) $value,
  70.             'float' => fn (string $value): float => (float) $value,
  71.         ][$castTo] ?? $defaultCaster;
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment