media_helper-2.0.0/media_helper.module
media_helper.module
<?php
/**
* @file
* Media Helper module.
*/
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Template\Attribute;
/**
* Implements hook_preprocess_HOOK().
*/
function media_helper_preprocess_responsive_image(array &$variables): void {
if (empty($variables['media_helper_attributes'])) {
return;
}
$passed_attributes = [];
if (empty($variables['output_image_tag'])) {
$always_img_attrs = \Drupal::service('media_helper')->getResponsiveImgTagAttributeNames();
foreach ($variables['media_helper_attributes'] as $attribute_name => $attribute_value) {
if (in_array($attribute_name, $always_img_attrs, TRUE)) {
$passed_attributes['img'][$attribute_name] = $attribute_value;
}
else {
$passed_attributes['picture'][$attribute_name] = $attribute_value;
}
}
}
else {
$passed_attributes['img'] = $variables['media_helper_attributes'];
}
foreach ($passed_attributes as $attribute_tag => $attributes) {
if (!$attributes) {
continue;
}
$tag_attributes = NULL;
if ($attribute_tag === 'img') {
if (!isset($variables['img_element']['#attributes'])) {
$variables['img_element']['#attributes'] = [];
}
$tag_attributes =& $variables['img_element']['#attributes'];
}
elseif ($attribute_tag === 'picture') {
if (!isset($variables['attributes'])) {
$variables['attributes'] = [];
}
$tag_attributes =& $variables['attributes'];
}
else {
throw new \LogicException('Unknown attribute tag "' . $$attribute_tag . '"');
}
if (!$tag_attributes) {
$tag_attributes = $attributes;
}
elseif (is_array($tag_attributes)) {
$tag_attributes = NestedArray::mergeDeep(
$tag_attributes,
$attributes instanceof Attribute ? $attributes->toArray() : $attributes
);
}
elseif ($tag_attributes instanceof Attribute) {
$tag_attributes->merge($attributes instanceof Attribute
? $attributes
: new Attribute($attributes)
);
}
else {
$attrs_type = is_object($tag_attributes)
? get_class($tag_attributes)
: gettype($tag_attributes);
throw new \LogicException('Unrecognized #attributes type ' . $attrs_type);
}
// Need to unset referenced variable so it isn't overwritten in the next
// cycle of the loop.
unset($tag_attributes);
}
}
/**
* Implements hook_preprocess_HOOK().
*/
function media_helper_preprocess_responsive_image_formatter(array &$variables): void {
if (!empty($variables['media_helper_attributes'])) {
$variables['responsive_image']['#media_helper_attributes'] = $variables['media_helper_attributes'];
}
}
/**
* Implements hook_theme_registry_alter().
*/
function media_helper_theme_registry_alter(array &$theme_registry): void {
if (isset($theme_registry['responsive_image_formatter'])) {
$theme_registry['responsive_image_formatter']['variables']['media_helper_attributes'] = [];
}
if (isset($theme_registry['responsive_image'])) {
$theme_registry['responsive_image']['variables']['media_helper_attributes'] = [];
}
}
