You are here

GinLbExtension.php in Gin Layout Builder 1.0.x

File

src/TwigExtension/GinLbExtension.php
View source
<?php

namespace Drupal\gin_lb\TwigExtension;

use Drupal\Core\Template\Attribute;
use Drupal\Core\Template\TwigExtension;
use Twig\TwigFunction;

/**
 * A class providing Gin Twig function.
 *
 * @package Drupal\gin_lb\TwigExtension
 */
class GinLbExtension extends TwigExtension {
  private static $ginLbClasses = NULL;

  /**
   * {@inheritdoc}
   */
  public function getFunctions() {
    return [
      new TwigFunction('glb_classes', [
        $this,
        'ginClasses',
      ]),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return 'gin_lb';
  }

  /**
   * Returns a list of all glb- prefixed classes.
   * The classes are generated by an postcss plugin.
   *
   * @return []
   *   The classes
   */
  private static function getGinLbClasses() {
    if (GinLbExtension::$ginLbClasses === NULL) {
      GinLbExtension::$ginLbClasses = json_decode(file_get_contents(__DIR__ . '/../classes.json'));
    }
    return GinLbExtension::$ginLbClasses;
  }

  /**
   * Replaces all theme classes with gin classes.
   *
   * @param \Drupal\Core\Template\Attribute $attribute
   *   Twig attributes.
   *
   * @return \Drupal\Core\Template\Attribute
   *   The replaced attributes.
   */
  public static function ginClasses(Attribute $attribute) {
    $gin_lb_classes = self::getGinLbClasses();
    if ($attribute
      ->getClass() === NULL) {
      return $attribute;
    }
    $renamed_classes = [];

    // These classes need to be kept for script purposes.
    // If this class has been styled, then we'll keep both classes: the original
    // and the custom glb one.
    $script_classes = [
      'form-autocomplete',
    ];
    foreach ($attribute
      ->getClass() as $class_string) {

      // $attribute->getClass returns multiple classes as one class.
      // To prefix this classes - explode it.
      $classes = explode(' ', $class_string);
      foreach ($classes as $class) {
        if (in_array('glb-' . $class, $gin_lb_classes)) {
          $renamed_classes[] = 'glb-' . $class;
          if (in_array($class, $script_classes)) {
            $renamed_classes[] = $class;
          }
        }
        else {
          $renamed_classes[] = $class;
        }
      }
    }
    $attribute
      ->setAttribute('class', $renamed_classes);
    return $attribute;
  }

}

Classes

Namesort descending Description
GinLbExtension A class providing Gin Twig function.