src/EventsSubscriber/System/EnvStartupLogSubscriber.php line 34

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventsSubscriber\System;
  4. use Psr\Log\LoggerInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. final class EnvStartupLogSubscriber implements EventSubscriberInterface
  9. {
  10.     private const SENSITIVE_KEY_PATTERN '/SECRET|PASSWORD|TOKEN|KEY|DSN|DATABASE_URL|PRIVATE|CREDENTIAL|AUTH|WEBHOOK|JWT/i';
  11.     private bool $wasLogged false;
  12.     public function __construct(
  13.         private readonly LoggerInterface $logger,
  14.     ) {
  15.     }
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             KernelEvents::REQUEST => [
  20.                 'onKernelRequest',
  21.                 2048,
  22.             ],
  23.         ];
  24.     }
  25.     public function onKernelRequest(RequestEvent $event): void
  26.     {
  27.         if (!$event->isMainRequest() || $this->wasLogged) {
  28.             return;
  29.         }
  30.         $this->wasLogged true;
  31.         $this->logger->info('Application startup environment variables', [
  32.             'env_vars' => $this->collectEnvironmentVariables(),
  33.         ]);
  34.     }
  35.     /**
  36.      * @return array<string, string>
  37.      */
  38.     private function collectEnvironmentVariables(): array
  39.     {
  40.         $values getenv();
  41.         if (!is_array($values)) {
  42.             return [];
  43.         }
  44.         ksort($values);
  45.         $result = [];
  46.         foreach ($values as $key => $value) {
  47.             if (!is_string($key)) {
  48.                 continue;
  49.             }
  50.             $normalizedValue is_scalar($value) ? (string) $value '[non-scalar]';
  51.             $result[$key] = $this->maskIfSensitive($key$normalizedValue);
  52.         }
  53.         return $result;
  54.     }
  55.     private function maskIfSensitive(string $keystring $value): string
  56.     {
  57.         if (preg_match(self::SENSITIVE_KEY_PATTERN$key) === 1) {
  58.             return '[masked]';
  59.         }
  60.         if (strlen($value) > 200) {
  61.             return sprintf('%s...[truncated]'substr($value0200));
  62.         }
  63.         return $value;
  64.     }
  65. }