Skip to content

settings.php: Port inline validation of environment variables to reusable object-oriented code

There's a lot of repetitive stuff in the settings.php like:

/**
 * Salt for one-time login links, cancel links, form tokens, etc.
 */
if (\getenv('DRUPAL_HASH_SALT') !== false) {

  if (\mb_strlen(\getenv('DRUPAL_HASH_SALT')) === 0) {

    throw new \UnexpectedValueException(
      'The "DRUPAL_HASH_SALT" environment variable cannot be set to an empty value if set!',
    );

  }

  $settings['hash_salt'] = \getenv('DRUPAL_HASH_SALT');

}

which repeats the same sorts of basic tasks over and over. Abstracting this into value objects of some sort and utilizing the Symfony Validator component would make for a more elegant and scalable solution. The Validator component supports applying groups of validators, and as an added syntactic bonus, it can do PHP attributes like so:

    #[Assert\NotBlank(groups: ['registration'])]
    #[Assert\Length(min: 7, groups: ['registration'])]
    private string $password;

which feels much easier to read.