dsfr4drupal-1.x-dev/src/Dsfr4DrupalPreRender.php
src/Dsfr4DrupalPreRender.php
<?php
namespace Drupal\dsfr4drupal;
use Drupal\Core\Render\Element;
use Drupal\Core\Security\TrustedCallbackInterface;
/**
* Implements trusted prerender callbacks for the "DSFR for Drupal" theme.
*
* @internal
*/
class Dsfr4DrupalPreRender implements TrustedCallbackInterface {
/**
* Prerender callback for Horizontal Tabs element.
*
* @param array $element
* The render array element.
*
* @return array
* The new render array element.
*/
public static function horizontalTabs(array $element): array {
return self::tabs($element, 'horizontal');
}
/**
* Prerender callback for Vertical Tabs element.
*
* @param array $element
* The render array element.
*
* @return array
* The new render array element.
*/
public static function verticalTabs(array $element): array {
return self::tabs($element, 'vertical');
}
/**
* Prerender callback for tabs element.
*
* @param array $element
* The render array element.
*
* @param string $orientation
* The tab orientation key.
*
* @return array
* The new render array element.
*/
private static function tabs(array $element, string $orientation): array {
$isDetails = isset($element['group']['#type']) && $element['group']['#type'] === 'details';
$existingGroups = isset($element['group']['#groups']) && is_array($element['group']['#groups']);
// If the horizontal/vertical tabs have a details group, add attributes to those
// details elements so they are styled as accordion items and have BEM classes.
if ($isDetails && $existingGroups) {
$groupKeys = Element::children($element['group']['#groups'], TRUE);
$groupKey = implode('][', $element['#parents']);
// Only check siblings against groups because we are only looking for
// group elements.
if (in_array($groupKey, $groupKeys)) {
$childrenKeys = Element::children($element['group']['#groups'][$groupKey], TRUE);
foreach ($childrenKeys as $childKey) {
$type = $element['group']['#groups'][$groupKey][$childKey]['#type'] ?? NULL;
if ($type === 'details') {
$element['group']['#groups'][$groupKey][$childKey]['#' . $orientation . '_tab_item'] = TRUE;
}
}
}
}
return $element;
}
/**
* {@inheritdoc}
*/
public static function trustedCallbacks(): array {
return [
'horizontalTabs',
'verticalTabs',
];
}
}
