dchadwick/web/themes/custom/dchadwick/dchadwick.theme
2025-03-15 17:25:17 -04:00

108 lines
2.7 KiB
PHP

<?php
use Drupal\node\NodeInterface;
/**
* Implements template_preprocess_html().
*/
function dchadwick_preprocess_html(&$variables) {
if (isset($variables['node_type'])) {
// Add node-TYPE class to the <body> element.
$variables['attributes']['class'][] = 'node-type-' . $variables['node_type'];
}
}
function dchadwick_preprocess_node__article(&$vars) {
$vars['#attached']['library'] = 'dchadwick/articles';
}
function dchadwick_preprocess_field(&$vars) {
if (isset($vars['field_name'])) {
$vars['attributes']['class'][] = $vars['field_name'];
}
}
function dchadwick_page_attachments_alter(&$page) {
// Attach brain.js to all pages? No reason at the moment.
$page['#attached']['library'][] = 'dchadwick/brainjs';
}
function dchadwick_preprocess_node__fighter(&$vars) {
$fighter_node = \Drupal::routeMatch()->getParameter('node');
if (!$fighter_node) {
return;
}
// Need to ensure the type here.
// Only operate if view mode is full.
$is_full_view = $vars['view_mode'] == 'default' ?? FALSE;
if (!$is_full_view) {
return;
}
assert($fighter_node instanceof NodeInterface);
assert($fighter_node->bundle() == 'fighter');
$personal_fields = [
'age',
'division',
'height',
'weight',
'reach',
'leg_reach',
];
$stats_fields = [
'knockouts',
'striking_accuracy',
'strikes_per_minute',
'sig_strike_defense',
'absorbed_per_min',
'standing_strikes',
'clinch_strikes',
'ground_strikes',
'grappling_accuracy',
'strikes_to_head',
'strikes_to_body',
'strikes_to_leg',
'knockdown_ratio',
'takedowns_per_15',
'takedown_defense',
'average_fight_time',
'first_round_finishes',
];
$vars['personal_info'] = get_field_values_from_node($fighter_node, $personal_fields);
$vars['stats'] = get_field_values_from_node($fighter_node, $stats_fields);
}
/**
* Extracts target field values from a node.
*
* @param NodeInterface $node
* The node.
*
* @param array[] $retrieve
* The fields to retrieve
*
* @return array[]
*/
function get_field_values_from_node(NodeInterface $node, array $retrieve): array {
$return_data = [];
foreach ($retrieve as $field_name) {
$field_name_with_prefix = "field_$field_name";
if ($field_name == 'division') {
if ($node->hasField($field_name_with_prefix)) {
$div_id = $node->get($field_name_with_prefix)->target_id;
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($div_id);
$return_data['division'] = $term->getName();
}
}
else {
if ($node->hasField($field_name_with_prefix)) {
$return_data[$field_name] = $node->{$field_name_with_prefix}->value;
}
}
}
return $return_data;
}