Files
VITEC-website/packages/vitec/Classes/UserFunc/CustomerlogosJsonRenderer.php
2026-08-14 10:36:36 +02:00

249 lines
9.2 KiB
PHP
Executable File

<?php
declare(strict_types=1);
namespace Evomedien\Vitec\UserFunc;
use Doctrine\DBAL\ParameterType;
use TYPO3\CMS\Core\Attribute\AsAllowedCallable;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\Service\FlexFormService;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Service\ImageService;
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
/**
* UserFunc: render the VITEC customer logos as JSON (headless).
*
* Output under content.customerlogos:
* { "layout": "list|grid|carousel|marquee", "logos": [ … ] }
*
* Selection logic:
* - no customers selected -> ALL logos, each with color:false (b/w)
* - customers selected -> the selected ones FIRST (selection order,
* color:true), followed by all remaining logos (color:false)
*
* `render()` = top-level plugin / page discovery. `renderForRecord()` = one
* specific tt_content row (reused by ContainerChildrenProcessor for nested
* plugins). Exception-safe.
*/
class CustomerlogosJsonRenderer
{
private ?ContentObjectRenderer $cObj = null;
/**
* TYPO3 v14 hands the ContentObjectRenderer over through this setter only -
* ContentObjectRenderer::callUserFunction() duck-types it with
* is_callable([$classObj, 'setContentObjectRenderer']). Without the method
* $this->cObj stays null, the cObj branch of render() never fires and the
* call falls through to page discovery, which picks the FIRST element of
* this CType on the page rather than the one actually being rendered.
*/
public function setContentObjectRenderer(ContentObjectRenderer $cObj): void
{
$this->cObj = $cObj;
}
private const TABLE = 'tx_vitec_domain_model_customer';
private const IMAGE_WIDTHS = [200, 400];
#[AsAllowedCallable]
public function render(string $content, array $conf): string
{
$row = is_array($this->cObj?->data ?? null) ? $this->cObj->data : null;
if ($row && (string)($row['CType'] ?? '') === 'vitec_customerlogos') {
return $this->renderForRecord($row);
}
$pageId = 0;
$request = $GLOBALS['TYPO3_REQUEST'] ?? null;
if ($request !== null) {
$pageInfo = $request->getAttribute('frontend.page.information');
if ($pageInfo !== null) {
$pageId = (int)$pageInfo->getId();
}
}
if ($pageId <= 0) {
$pageId = (int)($GLOBALS['TSFE']->id ?? 0);
}
if ($pageId <= 0) {
return '';
}
$qb = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tt_content');
$ces = $qb
->select('*')
->from('tt_content')
->where(
$qb->expr()->eq('pid', $qb->createNamedParameter($pageId, ParameterType::INTEGER)),
$qb->expr()->eq('CType', $qb->createNamedParameter('vitec_customerlogos', ParameterType::STRING)),
$qb->expr()->eq('deleted', 0),
$qb->expr()->eq('hidden', 0)
)
->executeQuery()
->fetchAllAssociative();
if (empty($ces)) {
return '';
}
return $this->renderForRecord($ces[0]);
}
/**
* @param array<string,mixed> $contentElement
*/
public function renderForRecord(array $contentElement): string
{
try {
$flexFormService = GeneralUtility::makeInstance(FlexFormService::class);
$flexFormData = $flexFormService->convertFlexFormContentToArray($contentElement['pi_flexform'] ?? '');
$settings = $flexFormData['settings'] ?? [];
$layout = (string)($settings['layout'] ?? 'grid');
$debugMode = (bool)($settings['debug'] ?? false);
$selectedUids = GeneralUtility::intExplode(',', (string)($settings['customers'] ?? ''), true);
$onlySelected = (bool)($settings['onlySelected'] ?? false);
$qb = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable(self::TABLE);
$rows = $qb
->select('*')
->from(self::TABLE)
->where(
$qb->expr()->eq('deleted', 0),
$qb->expr()->eq('hidden', 0)
)
->orderBy('sorting', 'ASC')
->executeQuery()
->fetchAllAssociative();
$byUid = [];
foreach ($rows as $r) {
$byUid[(int)$r['uid']] = $r;
}
// Selected customers first (selection order, in color), then the rest (b/w).
$logos = [];
foreach ($selectedUids as $uid) {
if (isset($byUid[$uid])) {
$logos[] = $this->serializeCustomer($byUid[$uid], true);
unset($byUid[$uid]);
}
}
if (!($onlySelected && $selectedUids !== [])) {
foreach ($byUid as $r) {
$logos[] = $this->serializeCustomer($r, false);
}
}
$response = [
'layout' => $layout,
'logos' => $logos,
];
if ($debugMode) {
$response['debug'] = [
'count' => count($logos),
'selected' => $selectedUids,
'settings' => $settings,
];
}
return (string)json_encode($response);
} catch (\Throwable $e) {
return '';
}
}
/**
* @param array<string,mixed> $r
* @return array<string,mixed>
*/
private function serializeCustomer(array $r, bool $color): array
{
return [
'id' => (int)$r['uid'],
'name' => (string)($r['title'] ?? ''),
'emphasized' => (bool)($r['emphasize_logo'] ?? false),
'color' => $color,
'logo' => $this->logo((int)$r['uid']),
];
}
/**
* FAL logo with small srcset; SVGs are delivered unprocessed.
*
* @return array<string,mixed>|null
*/
private function logo(int $customerUid): ?array
{
try {
$qb = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('sys_file_reference');
$ref = $qb
->select('uid', 'title', 'alternative', 'crop')
->from('sys_file_reference')
->where(
$qb->expr()->eq('tablenames', $qb->createNamedParameter(self::TABLE, ParameterType::STRING)),
$qb->expr()->eq('fieldname', $qb->createNamedParameter('logo', ParameterType::STRING)),
$qb->expr()->eq('uid_foreign', $qb->createNamedParameter($customerUid, ParameterType::INTEGER)),
$qb->expr()->eq('deleted', 0),
$qb->expr()->eq('hidden', 0)
)
->orderBy('sorting_foreign')
->setMaxResults(1)
->executeQuery()
->fetchAssociative();
if (!$ref) {
return null;
}
$resourceFactory = GeneralUtility::makeInstance(ResourceFactory::class);
$imageService = GeneralUtility::makeInstance(ImageService::class);
$fileReference = $resourceFactory->getFileReferenceObject((int)$ref['uid']);
if (str_contains((string)$fileReference->getMimeType(), 'svg')) {
// SVG: no processing/srcset — deliver the file as-is.
return [
'uid' => (int)$ref['uid'],
'url' => (string)$fileReference->getPublicUrl(),
'title' => (string)($ref['title'] ?? ''),
'alternative' => (string)($ref['alternative'] ?? ''),
'srcset' => [],
'properties' => ['mimeType' => $fileReference->getMimeType()],
];
}
$srcset = [];
foreach (self::IMAGE_WIDTHS as $width) {
$variant = $imageService->applyProcessingInstructions(
$fileReference,
['width' => $width, 'crop' => $ref['crop'] ?? null, 'fileExtension' => 'webp']
);
$srcset[] = ['url' => $imageService->getImageUri($variant), 'width' => $width, 'descriptor' => $width . 'w'];
}
$default = $imageService->applyProcessingInstructions(
$fileReference,
['width' => 400, 'crop' => $ref['crop'] ?? null, 'fileExtension' => 'webp']
);
return [
'uid' => (int)$ref['uid'],
'url' => $imageService->getImageUri($default),
'title' => (string)($ref['title'] ?? ''),
'alternative' => (string)($ref['alternative'] ?? ''),
'srcset' => $srcset,
'properties' => [
'width' => $fileReference->getProperty('width'),
'height' => $fileReference->getProperty('height'),
'mimeType' => $fileReference->getProperty('mime_type'),
],
];
} catch (\Throwable $e) {
return null;
}
}
}