Skip to content

Instantly share code, notes, and snippets.

@maikschneider
Created November 27, 2023 15:51
Show Gist options
  • Select an option

  • Save maikschneider/8b3d24273eb87f482049a3dfd6016d2f to your computer and use it in GitHub Desktop.

Select an option

Save maikschneider/8b3d24273eb87f482049a3dfd6016d2f to your computer and use it in GitHub Desktop.
<?php
namespace Vendor\MyExtension\Command;
use Doctrine\DBAL\Result;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\DataHandling\Model\RecordStateFactory;
use TYPO3\CMS\Core\DataHandling\SlugHelper;
use TYPO3\CMS\Core\Utility\GeneralUtility;
class SlugUpdateCommand extends Command
{
private const TABLES = [
'tx_myextension_domain_model_event' => 'slug',
'tx_news_domain_model_news' => 'path_segment',
];
public function __construct(protected ConnectionPool $connectionPool, string $name = null)
{
parent::__construct($name);
}
public function execute(InputInterface $input, OutputInterface $output): int
{
foreach (self::TABLES as $table => $slugField) {
// abort if no updated for this table is needed
$elements = $this->getElementsForTable($table);
if (!$elements instanceof Result || !$elements->rowCount()) {
continue;
}
// init SlugHelper for this table
$fieldConfig = $GLOBALS['TCA'][$table]['columns'][$slugField]['config'];
/** @var SlugHelper $slugHelper */
$slugHelper = GeneralUtility::makeInstance(
SlugHelper::class,
$table,
$slugField,
$fieldConfig
);
// init QueryBuilder
$connection = $this->connectionPool->getConnectionForTable($table);
$queryBuilder = $connection->createQueryBuilder();
while ($record = $elements->fetchAssociative()) {
$pid = (int)$record['pid'];
$uid = (int)$record['uid'];
// generate unique slug for record
$value = $slugHelper->generate($record, $pid);
$state = RecordStateFactory::forName($table)
->fromArray($record, $pid, $uid);
$slug = $slugHelper->buildSlugForUniqueInPid($value, $state);
// update slug field of record
$queryBuilder->update($table)
->where(
$queryBuilder->expr()->eq(
'uid',
$queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
)
)
->set($slugField, $slug);
$queryBuilder->execute();
}
}
return Command::SUCCESS;
}
private function getElementsForTable(string $table): int|Result
{
$connection = $this->connectionPool->getConnectionForTable($table);
$queryBuilder = $connection->createQueryBuilder();
$queryBuilder->getRestrictions()->removeAll();
return $queryBuilder->select('*')
->from($table)
->execute();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment