semanticui-8.x-1.x-dev/preprocess/field__comment.preprocess.inc
preprocess/field__comment.preprocess.inc
<?php
/**
* @file
* Contains preprocess functions for comment field.
*/
use Drupal\Component\Utility\NestedArray;
/**
* Implements hook_preprocess_HOOK().
*
* Updates comments to use Fomantic UI markup (including threaded version).
*/
function semanticui_preprocess_field__comment(&$variables) {
if (empty($variables['element']['#object']->getFieldDefinitions()['comment']) || !$variables['element']['#object']->getFieldDefinitions()['comment']->getSetting('default_mode')) {
return;
}
foreach ($variables['comments'] as $cid => $comment) {
/** @var \Drupal\comment\CommentInterface $comment_entity */
$comment_entity = $comment['#comment'] ?? NULL;
if (!$comment_entity || !$comment_entity->getParentComment()) {
continue;
}
// Unset default indentation wrapper even if there is no parent comments.
// The case may happen if thread is paged and the page start with child
// comment.
$variables['comments'][$cid]['#pre_render'][] = 'semanticui_update_comment_indentation';
$parent_ids = semanticui_comment_get_parents($comment_entity->getParentComment()->id(), $variables['comments']);
if (!$parent_ids) {
continue;
}
$parent = NestedArray::getValue($variables['comments'], $parent_ids);
if (!isset($parent['#subcomments'])) {
$parent['#subcomments'] = [
'#pre_render' => $variables['comments']['#pre_render'],
];
NestedArray::setValue($variables['comments'], $parent_ids, $parent);
}
$parent['#subcomments'][$cid] = $variables['comments'][$cid];
NestedArray::setValue($variables['comments'], $parent_ids, $parent);
unset($variables['comments'][$cid]);
}
}
/**
* Pre-render callback to remove default comment wrapper.
*/
function semanticui_update_comment_indentation(array $build_list) {
unset($build_list['#suffix']);
unset($build_list['#prefix']);
return $build_list;
}
/**
* Helper function to get all parent comments.
*
* @param int $pid
* Parent comment id.
* @param array $comments
* An array of all comments to look for parents in.
*
* @return array|null
* Returned result contains an array of all parents or NULL if parent was not
* found in the provided comments array (this situation is possible when
* comments thread is divided on multiple pages).
*/
function semanticui_comment_get_parents($pid, array $comments) {
if (array_key_exists($pid, $comments)) {
return [$pid];
}
foreach ($comments as $cid => $comment) {
if (!empty($comment['#subcomments'])) {
$parents = [
$cid,
'#subcomments',
];
$sub_parents = semanticui_comment_get_parents($pid, $comment['#subcomments']);
if (!empty($sub_parents)) {
return array_merge($parents, $sub_parents);
}
}
}
return NULL;
}
