Config validation

Drupal's next leap?


Wim Leers
Senior Principal Software Engineer
Acquia logo's Drupal Acceleration Team

A brief history of config in Drupal
erastorageblobbiness
2004variable tableextremely๐Ÿ™ˆ
2012YAML filesdiffable๐Ÿค“๐”
2013[โ€ฆ] + schemaintrospectable๐Ÿค”๐Ÿ’ก
2014config table + [โ€ฆ]unchanged๐ŸŽ๏ธ
2017[โ€ฆ] + [โ€ฆ] + constraintsvalidatableโœ…

Trend: more structure

  • introspectable  (๐Ÿ‘‹ variable module)
  • translatable (๐Ÿ‘‹ i18n module)
  • exportable    (๐Ÿ‘‹ ctools exportables)

type: uuid

๐Ÿ‘†

the only validatable config type

๐Ÿ˜ฑ

Why?

๐Ÿคทโ€โ™€๏ธ

  • Writing configuration via JSON:API
  • Admin UI improvements ๐Ÿชฆ JS Admin UI
  • Reliable config_split, config_filter โ€ฆ
  • Recipes Initiative
  • Automatic Updates Initiative
  • Ambitious site builder experiences

Config schema 101

๐Ÿ“š

type: uuid use

config_entity:
  type: mapping
  mapping:
    uuid:
      type: uuid
      label: 'UUID'
  โ€ฆ

type: uuid definition

# A UUID.
uuid:
  type: string
  label: 'UUID'
  constraints:
    Uuid: {}
core/config/schema/core.data_types.schema.yml
"Uuid" ๐Ÿ‘‰ a @Constraint plugin ID
namespace Drupal\Core\Validation\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraints\Uuid;
use Symfony\Component\Validator\Constraints\UuidValidator;

/**
 * Validates a UUID.
 *
 * @Constraint(
 *   id = "Uuid",
 *   label = @Translation("Universally Unique Identifier", context = "Validation"),
 * )
 */
class UuidConstraint extends Uuid {

  /**
   * {@inheritdoc}
   */
  public function validatedBy() {
    return UuidValidator::class;
  }

  public $message = 'This is not a valid UUID.';

}
namespace Symfony\Component\Validator\Constraints;

class UuidValidator extends ConstraintValidator {

    public function validate(mixed $value, Constraint $constraint) {
        if (!$constraint instanceof Uuid) {
            throw new UnexpectedTypeException($constraint, Uuid::class);
        }
        if (!\is_scalar($value) && !$value instanceof \Stringable) {
            throw new UnexpectedValueException($value, 'string');
        }
        โ€ฆ
    }

}

๐Ÿง‘โ€๐ŸŽ“๐Ÿฅณ

Live demo #1

d.o/project/config_inspector
drush config:inspect
drush config:inspect --todo
drush config:inspect --filter-keys=node.type.article \
                     --detail \
                     --list-constraints

Live demo #2

Validation constraints in forms

  1. Implement ConfigFormBase's optional methods since Drupal 10.2: #3373502
  2. ๐Ÿ’ฐ๐ŸŒˆ
  1. Implement ConfigFormBase's optional methods since Drupal 10.2: #3373502
  2. ๐Ÿ’ฐ๐ŸŒˆ
  3. Optional: ConfigEvents::SAVE subscriber to validate your config
  4. ๐Ÿฅณ๐Ÿฅ‡

๐Ÿ™

๐Ÿ™‡๐Ÿปโ€โ™‚๏ธ

META#2164373
๐Ÿ‘€  โคต
๐ŸŸข Required values#3364109
๐ŸŸก Required keys#3364108
๐Ÿšข Validate in tests#3361534
Which config changes have caused outages for YOU? ๐Ÿซต