<?php

/**
 * @file
 * Contains d_p_side_by_side module.
 */

use Drupal\Core\Entity\EntityTypeInterface;

/**
 * Implements hook_theme().
 */
function d_p_side_by_side_theme($existing, $type, $theme, $path) {
  return [
    'paragraph__d_p_side_by_side' => [
      'base hook' => 'paragraph',
    ],
    'field__field_d_p_sbs_items' => [
      'base hook' => 'field',
    ],
  ];
}

/**
 * Implements hook_entity_info_alter().
 */
function d_p_side_by_side_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'paragraph' && !empty($fields['field_d_p_sbs_items'])) {
    /** @var \Drupal\field\Entity\FieldConfig $field */
    $field = $fields['field_d_p_sbs_items'];
    $field->addConstraint('AllItemsRequired', [
      'number' => $field->getFieldStorageDefinition()->getCardinality(),
      'name' => $field->label(),
    ]);
  }
}

/**
 * Implements hook_preprocess().
 *
 * Check if side by side contains non-empty header.
 */
function d_p_side_by_side_preprocess_paragraph__d_p_side_by_side(&$variables, $hook) {
  $variables['has_header'] = FALSE;
  if (isset($variables['content']['field_d_long_text'][0]) || isset($variables['content']['field_d_main_title'][0])) {
    $variables['has_header'] = TRUE;
  }
}
