Verified Commit df9baa95 authored by Dave Long's avatar Dave Long
Browse files

Issue #3520944 by phenaproxima, wim leers, borisson_, longwave: Make menu...

Issue #3520944 by phenaproxima, wim leers, borisson_, longwave: Make menu blocks (block.settings.system_menu_block:*) fully validatable
parent 3520cc8f
Loading
Loading
Loading
Loading
Loading
+28
Changes for core/lib/Drupal/Core/Menu/Plugin/Validation/Constraint/MenuLinkDepthConstraint.php: 28 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

declare(strict_types=1);

namespace Drupal\Core\Menu\Plugin\Validation\Constraint;

use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Validation\Attribute\Constraint;
use Drupal\Core\Validation\Plugin\Validation\Constraint\RangeConstraint;

/**
 * Validates the link depth of a menu tree.
 */
#[Constraint(
  id: 'MenuLinkDepth',
  label: new TranslatableMarkup('Menu link depth', options: ['context' => 'Validation']),
  type: ['integer'],
)]
class MenuLinkDepthConstraint extends RangeConstraint {

  /**
   * The initial level of menu items that are being exposed (zero-based).
   *
   * @var string|int
   */
  public string|int $baseLevel = 0;

}
+68
Changes for core/lib/Drupal/Core/Menu/Plugin/Validation/Constraint/MenuLinkDepthConstraintValidator.php: 68 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

declare(strict_types=1);

namespace Drupal\Core\Menu\Plugin\Validation\Constraint;

use Drupal\Core\Config\Schema\TypeResolver;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Menu\MenuLinkTreeInterface;
use Drupal\Core\Validation\Plugin\Validation\Constraint\RangeConstraintValidator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\RuntimeException;

/**
 * Validates the MenuLinkDepthConstraint constraint.
 */
class MenuLinkDepthConstraintValidator extends RangeConstraintValidator implements ContainerInjectionInterface {

  public function __construct(
    protected readonly MenuLinkTreeInterface $menuLinkTree,
  ) {}

  /**
   * {@inheritdoc}
   */
  public function validate(mixed $value, Constraint $constraint): void {
    assert($constraint instanceof MenuLinkDepthConstraint);

    // The depth can never exceed the maximum depth of a menu tree.
    $constraint->max = $this->menuLinkTree->maxDepth();

    $base_level = $constraint->baseLevel;
    // The base level might be a dynamic name that needs to be resolved.
    if (is_string($base_level)) {
      $base_level = TypeResolver::resolveDynamicTypeName($base_level, $this->context->getObject());
    }
    if (!is_numeric($base_level)) {
      throw new RuntimeException('The `base` option must be a number, or an expression that resolves to one.');
    }
    // Clamp $base_level (which is zero-based) to at least 0 and no more than
    // the maximum depth of a menu tree.
    $base_level = max(0, $base_level);
    $base_level = min($base_level, $constraint->max);

    $constraint->max -= $base_level;
    // We're validating a depth -- i.e., the number of levels in the menu tree
    // that should be visible. 0 effectively means "show only one level", but
    // it's not a valid value: we can't show 0 levels of the tree, after all (
    // the minimum number of levels we *could* show is 1). The discrepancy is
    // due to $base_level being zero-based, so adjust for that.
    if ($constraint->max === 0) {
      $constraint->max = 1;
    }

    parent::validate($value, $constraint);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): static {
    return new static(
      $container->get(MenuLinkTreeInterface::class),
    );
  }

}
+19
Changes for core/modules/block/block.post_update.php: 19 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -34,3 +34,22 @@ function block_post_update_make_weight_integer(array &$sandbox = []): void {
      return FALSE;
    });
}

/**
 * Updates the `depth` setting to NULL if it is 0 in any menu blocks.
 */
function block_post_update_set_menu_block_depth_to_null_if_zero(array &$sandbox = []): void {
  \Drupal::classResolver(ConfigEntityUpdater::class)
    ->update($sandbox, 'block', function (BlockInterface $block): bool {
      if ($block->getPlugin()->getBaseId() === 'system_menu_block') {
        $settings = $block->get('settings');
        // Use `empty()` to account for either integer 0, or '0'.
        if (empty($settings['depth'])) {
          $settings['depth'] = NULL;
        }
        $block->set('settings', $settings);
        return TRUE;
      }
      return FALSE;
    });
}
+1 −1
Changes for core/modules/block/migrations/d6_block.yml: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -127,6 +127,6 @@ destination:
  plugin: entity:block
migration_dependencies:
  required:
    - menu
    - d6_menu
    - d6_custom_block
    - d6_user_role
+38 −1
Changes for core/modules/block/src/Plugin/migrate/process/BlockSettings.php: 38 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -2,11 +2,14 @@

namespace Drupal\block\Plugin\migrate\process;

use Drupal\Core\Block\BlockManagerInterface;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\migrate\Attribute\MigrateProcess;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
use Symfony\Component\DependencyInjection\ContainerInterface;

// cspell:ignore whois

@@ -14,7 +17,36 @@
 * Determines the block settings.
 */
#[MigrateProcess('block_settings')]
class BlockSettings extends ProcessPluginBase {
class BlockSettings extends ProcessPluginBase implements ContainerFactoryPluginInterface {

  /**
   * The block manager service.
   *
   * @var \Drupal\Core\Block\BlockManagerInterface
   */
  protected readonly BlockManagerInterface $blockManager;

  public function __construct(array $configuration, $plugin_id, $plugin_definition, ?BlockManagerInterface $blockManager = NULL) {
    if (empty($blockManager)) {
      @trigger_error('Calling ' . __METHOD__ . '() without the $blockManager parameter is deprecated in drupal:11.2.0 and must be provided in drupal:12.0.0. See https://www.drupal.org/node/3522023', E_USER_DEPRECATED);
      $blockManager = \Drupal::service(BlockManagerInterface::class);
    }
    $this->blockManager = $blockManager;

    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get(BlockManagerInterface::class),
    );
  }

  /**
   * {@inheritdoc}
@@ -61,6 +93,11 @@ public function transform($value, MigrateExecutableInterface $migrate_executable
        $settings['items_per_page'] = $old_settings['user']['max_list_count'];
        break;
    }

    // Let the block plugin fill in any missing settings.
    $settings = $this->blockManager->createInstance($plugin, $settings)
      ->getConfiguration();

    return $settings;
  }

Loading