function AddComponent::apply

Overrides ConfigActionPluginInterface::apply

File

core/modules/layout_builder/src/Plugin/ConfigAction/AddComponent.php, line 87

Class

AddComponent
Adds a component to a layout builder section.

Namespace

Drupal\layout_builder\Plugin\ConfigAction

Code

public function apply(string $configName, mixed $value) : void {
    assert(is_array($value));
    $section_delta = $value['section'];
    $position = $value['position'];
    assert(is_int($section_delta));
    assert(is_int($position));
    $entity = $this->configManager
        ->loadConfigEntityByName($configName);
    if (!$entity instanceof SectionListInterface) {
        throw new ConfigActionException("No entity found for applying the addComponentToLayout action.");
    }
    $section = $entity->getSection($section_delta);
    $component = $value['component'];
    $region = $component['default_region'] ?? NULL;
    if (array_key_exists('region', $component) && is_array($component['region'])) {
        // Since the recipe author might not know ahead of time what layout the
        // section is using, they should supply a map whose keys are layout IDs
        // and values are region names, so we know where to place this component.
        // If the section layout ID is not in the map, they should supply the
        // name of a fallback region. If all that fails, give up with an
        // exception.
        $region = $component['region'][$section->getLayoutId()] ?? $component['default_region'] ?? throw new ConfigActionException("Cannot determine which region of the section to place this component into, because no default region was provided.");
    }
    if ($region === NULL) {
        throw new ConfigActionException("Cannot determine which region of the section to place this component into, because no region was provided.");
    }
    if (!isset($value['component']['configuration']) || !isset($value['component']['configuration']['id'])) {
        throw new ConfigActionException("Cannot determine the component configuration, or misses a plugin ID.");
    }
    // If no weight were set, there would be a warning. So we set a
    // default, which will be overridden in insertComponent anyway.
    // We also need to generate the UUID here, or it could be null.
    $uuid = $component['uuid'] ?? $this->uuidGenerator
        ->generate();
    $component = new SectionComponent($uuid, $region, $component['configuration'], $component['additional'] ?? []);
    // If the position is higher than the number of components, just put it last
    // instead of failing.
    $position = min($position, count($section->getComponentsByRegion($region)));
    $section->insertComponent($position, $component);
    $entity->setSection($section_delta, $section);
    $entity->save();
}

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