bootstrap_components_toolkit-1.0.0/src/BoostrapComponentsToolkitTwigExtension.php
src/BoostrapComponentsToolkitTwigExtension.php
<?php
namespace Drupal\bootstrap_components_toolkit;
use Drupal\Core\Template\Attribute;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* Twig extension.
*/
class BoostrapComponentsToolkitTwigExtension extends AbstractExtension {
/**
* {@inheritdoc}
*/
public function getFunctions() {
return [
new TwigFunction('safe_create_attribute', [$this, 'safeCreateAttribute']),
new TwigFunction('get_contrast_color', [$this, 'getContrastColor']),
];
}
/**
* Detects if the attributes are present and generate or populate them.
*
* This works with a higher lever of uncertainty than core's create_attribute
* twig function, as it can accept three different scenarios: no attributes,
* attributes as an array, attributes already as an Attributes object. In
* any case, it will return a valid attributes object.
*
* @param mixed $attributes
* An Attributes object or array.
*
* @return \Drupal\Core\Template\Attribute
* An Attributes object.
*/
public function safeCreateAttribute($attributes): Attribute {
if ($attributes instanceof Attribute) {
return $attributes;
}
elseif (is_array($attributes)) {
return new Attribute($attributes);
}
else {
return new Attribute();
}
}
/**
* Tries to find the contrast color value for a given color keyword.
*
* This works in conjuction with the theme settings that allow the user to
* define, per theme, how is each Bootstrap color keyword supposed to
* contrast against a text.
*
* @param string $color_name
* An Bootstrap color keyword.
*
* @return string|null
* Either 'dark', 'light' or NULL if the color has no match.
*/
public function getContrastColor(string $color_name): ?string {
$result = NULL;
// Try to find the contrast color on the theme settings.
$contrast_color = theme_get_setting("contrast-$color_name");
if (!empty($contrast_color)) {
$result = $contrast_color;
}
return $result;
}
}
