function ComponentNodeVisitor::validateSlots

Same name in this branch
  1. 11.x core/modules/sdc/src/Twig/ComponentNodeVisitor.php \Drupal\sdc\Twig\ComponentNodeVisitor::validateSlots()
Same name and namespace in other branches
  1. 10 core/modules/sdc/src/Twig/ComponentNodeVisitor.php \Drupal\sdc\Twig\ComponentNodeVisitor::validateSlots()
  2. 10 core/lib/Drupal/Core/Template/ComponentNodeVisitor.php \Drupal\Core\Template\ComponentNodeVisitor::validateSlots()

Performs a cheap validation of the slots in the template.

It validates them against the JSON Schema provided in the component definition file and massaged in the ComponentMetadata class. We don't use the JSON Schema validator because we just want to validate required and undeclared slots. This cheap validation lets us validate during runtime even in production.

Throws

\Drupal\Core\Render\Component\Exception\InvalidComponentException When the slots don't pass validation.

1 call to ComponentNodeVisitor::validateSlots()
ComponentNodeVisitor::leaveNode in core/lib/Drupal/Core/Template/ComponentNodeVisitor.php

File

core/lib/Drupal/Core/Template/ComponentNodeVisitor.php, line 139

Class

ComponentNodeVisitor
Provides a ComponentNodeVisitor to change the generated parse-tree.

Namespace

Drupal\Core\Template

Code

protected function validateSlots(Component $component, Node $node) : void {
    $metadata = $component->metadata;
    if (!$metadata->mandatorySchemas) {
        return;
    }
    $slot_definitions = $metadata->slots;
    $ids_available = array_keys($slot_definitions);
    $undocumented_ids = [];
    try {
        $it = $node->getIterator();
    } catch (\Exception $e) {
        return;
    }
    if ($it instanceof \SeekableIterator) {
        while ($it->valid()) {
            $provided_id = $it->key();
            if (!in_array($provided_id, $ids_available, TRUE)) {
                $undocumented_ids[] = $provided_id;
            }
            $it->next();
        }
    }
    // Now build the error message.
    $error_messages = [];
    if (!empty($undocumented_ids)) {
        $error_messages[] = sprintf('We found an unexpected slot that is not declared: [%s]. Declare them in "%s.component.yml".', implode(', ', $undocumented_ids), $component->machineName);
    }
    if (!empty($error_messages)) {
        $message = implode("\n", $error_messages);
        throw new InvalidComponentException($message);
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.