<?php

/**
 * @file
 * Add "bem" function for Pattern Lab & Drupal.
 */

use Twig\TwigFunction;

// phpcs:ignore DrupalPractice.CodeAnalysis.VariableAnalysis
$function = new TwigFunction('bem', function (
  ?string $block = '',
  ?string $element = '',
  ?array $modifiers = [],
  ?array $extraClasses = [],
) {
  $classes = [];

  if ($block) {
    $baseClass = $element ? $block . '__' . $element : $block;
    $classes[] = $baseClass;
    if (is_array($modifiers) && !empty($modifiers)) {
      foreach (array_filter($modifiers) as $modifier) {
        $classes[] = $baseClass . '--' . $modifier;
      }
    }
  }
  else {
    if ($element) {
      $classes[] = $element;
      if (is_array($modifiers) && !empty($modifiers)) {
        foreach (array_filter($modifiers) as $modifier) {
          $classes[] = $element . '--' . $modifier;
        }
      }
    }
  }

  // If extra non-BEM classes are added.
  if (isset($extraClasses)) {
    $classes = array_merge($classes, $extraClasses);
  }

  return $classes;
}, ['is_safe' => ['html']]);
