Files
VITEC-website/packages/vitec/Classes/Command/NormalizeSlugsCommand.php
T
orascheandClaude Fable 5 cbe46cdba2 Megamenu page-tree panels; generic slug normaliser
- evo_megamenu_json: new entry layout "pagetree" - the panel columns
  mirror the live subtree of the page the entry links to (one child per
  column, grandchildren as items, getMenu() restrictions apply), so the
  menu can never age against the page structure again. The stale
  9-market panel after the markets realign was the trigger. Curated
  columns are ignored on this layout; teasers and the featured slot
  stay editorial. Same columns shape in the payload - front ends need
  no change beyond knowing the new layout string
- new vitec:normalize-slugs --root=<slug> [--style=plain|and]:
  recursively realigns every slug below a root to
  <parent-slug>/<slugified-title>, cascading, with a sibling-collision
  warning; EXT:redirects covers the old URLs. TYPO3's slug generator
  keeps slashes from page titles (third hit: rtcc-/-rtic), this sweeps
  a whole tree. Run on /solutions: four fixes, including the
  long-standing passenger page and solution page 467. The misspelled
  "engagament" slug stays deliberately - it follows the page title and
  is fixed in the coordinated typo task

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-10-23 14:10:57 +02:00

134 lines
6.2 KiB
PHP

<?php
declare(strict_types=1);
namespace Evomedien\Vitec\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use TYPO3\CMS\Core\Core\Bootstrap;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\DataHandling\DataHandler;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* Normalises every page slug below a root to <parent-slug>/<slugified-title>,
* recursively and cascading (a fixed parent slug carries into its children).
* EXT:redirects covers the old URLs automatically.
*
* Why: TYPO3's own slug generator KEEPS slashes that live in page titles
* ("RTCC / RTIC" -> rtcc-/-rtic), which breaks routes and canonicals - the
* defect hit us three times (passenger page, solution page 467, RTCC).
* This command repairs a whole subtree in one sweep.
*
* --style picks the ampersand convention of the tree:
* plain "A & B" -> a-b (TYPO3 default, used below /solutions)
* and "A & B" -> a-and-b (used below /markets since the 10-23 align)
* Do not mix styles within one tree: the wrong style renames EVERY page.
*
* vendor/bin/typo3 vitec:normalize-slugs --root=/solutions
* vendor/bin/typo3 vitec:normalize-slugs --root=/solutions --apply
*/
#[AsCommand(
name: 'vitec:normalize-slugs',
description: 'Normalise page slugs below a root to parent-slug/title-slug (dry-run by default)'
)]
final class NormalizeSlugsCommand extends Command
{
/** Page types that carry no meaningful slug of their own. */
private const SKIP_DOKTYPES = [199, 254, 255];
protected function configure(): void
{
$this->addOption('root', null, InputOption::VALUE_REQUIRED, 'Slug of the root page, e.g. /solutions');
$this->addOption('style', null, InputOption::VALUE_REQUIRED, "Ampersand style: 'plain' (A & B -> a-b) or 'and' (-> a-and-b)", 'plain');
$this->addOption('apply', null, InputOption::VALUE_NONE, 'Write changes (default: dry run)');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
Bootstrap::initializeBackendAuthentication();
$apply = (bool)$input->getOption('apply');
$rootSlug = rtrim((string)$input->getOption('root'), '/');
$style = (string)$input->getOption('style') === 'and' ? 'and' : 'plain';
if ($rootSlug === '') {
$output->writeln('<error>--root is required (e.g. --root=/solutions)</error>');
return Command::FAILURE;
}
$connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('pages');
$root = $connection->fetchAssociative('SELECT uid, slug FROM pages WHERE deleted = 0 AND slug = ?', [$rootSlug]);
if (!$root) {
$output->writeln('<error>No page with slug ' . $rootSlug . '</error>');
return Command::FAILURE;
}
$output->writeln(($apply ? 'APPLY' : 'DRY-RUN') . ' · root ' . $rootSlug . ' (uid ' . (int)$root['uid'] . ') · style ' . $style);
$datamap = [];
$changes = 0;
$this->walk($connection, (int)$root['uid'], $rootSlug, $style, $datamap, $changes, $output);
if ($changes === 0) {
$output->writeln('All slugs already normalised.');
return Command::SUCCESS;
}
if (!$apply) {
$output->writeln("\n" . $changes . ' change(s). DRY RUN - nothing written. Add --apply to write.');
return Command::SUCCESS;
}
$dataHandler = GeneralUtility::makeInstance(DataHandler::class);
$dataHandler->start($datamap, []);
$dataHandler->process_datamap();
if ($dataHandler->errorLog !== []) {
$output->writeln('<error>DataHandler: ' . implode(' | ', $dataHandler->errorLog) . '</error>');
return Command::FAILURE;
}
$output->writeln('<info>' . $changes . ' slug(s) written (redirects follow). Flush the cache: vendor/bin/typo3 cache:flush</info>');
return Command::SUCCESS;
}
/**
* Depth-first: the parent's EFFECTIVE (possibly just-fixed) slug prefixes
* the children. Collisions between siblings get a numeric suffix and a
* warning - that needs an editorial look, never silent overwriting.
*
* @param array<string,array<int,array<string,mixed>>> $datamap
*/
private function walk($connection, int $parentUid, string $parentSlug, string $style, array &$datamap, int &$changes, OutputInterface $output): void
{
$taken = [];
foreach ($connection->fetchAllAssociative(
'SELECT uid, title, slug, doktype FROM pages WHERE deleted = 0 AND pid = ? AND sys_language_uid IN (0,-1) ORDER BY sorting',
[$parentUid]
) as $child) {
if (in_array((int)$child['doktype'], self::SKIP_DOKTYPES, true)) {
$this->walk($connection, (int)$child['uid'], $parentSlug, $style, $datamap, $changes, $output);
continue;
}
$expected = $parentSlug . '/' . $this->slugify((string)$child['title'], $style);
if (isset($taken[$expected])) {
$suffixed = $expected . '-' . ((int)$child['uid']);
$output->writeln(' <comment>! sibling collision on ' . $expected . ' - "' . (string)$child['title'] . '" (uid ' . (int)$child['uid'] . ') gets ' . $suffixed . ', review editorially</comment>');
$expected = $suffixed;
}
$taken[$expected] = true;
if ((string)$child['slug'] !== $expected) {
$datamap['pages'][(int)$child['uid']]['slug'] = $expected;
$changes++;
$output->writeln(sprintf(' ~ "%s" (uid %d) %s -> %s', (string)$child['title'], (int)$child['uid'], (string)$child['slug'], $expected));
}
$this->walk($connection, (int)$child['uid'], $expected, $style, $datamap, $changes, $output);
}
}
private function slugify(string $value, string $style): string
{
$value = mb_strtolower(trim($value));
$value = str_replace('&', $style === 'and' ? ' and ' : ' ', $value);
return trim((string)preg_replace('/[^a-z0-9]+/', '-', $value), '-');
}
}