fix(extra-features): Add attributes & styles to displaySvgIcon method

This commit is contained in:
2025-12-31 15:16:21 +01:00
parent e2c4f265c2
commit ea9b67ffc5

View File

@ -192,6 +192,7 @@ class SmartyHelperFunctions
}
/* CUSTOM ADDITIONS BELOW */
@ -212,14 +213,12 @@ class SmartyHelperFunctions
{svg_icon file='person.svg'}
*/
// Grab svg under falcon/_dev/img and display an error if not found
if (empty($params['file'])) {
return '';
}
// The path to the icons directory
$icon_path = _PS_THEME_DIR_ . '/_dev/img/' . basename($params['file']);
// If there aint an image, display a basic error message on dev mode
if (!is_file($icon_path)) {
if (defined('_PS_MODE_DEV_') && _PS_MODE_DEV_) {
return 'Invalid SVG path: ' . htmlspecialchars($icon_path);
@ -229,40 +228,49 @@ class SmartyHelperFunctions
$svg_content = file_get_contents($icon_path);
// Define SVG attributes that should be replaced/added
$svg_attributes = [
'width',
'height',
'fill',
'stroke',
'stroke-width',
'opacity',
'viewBox',
];
foreach ($svg_attributes as $attr) {
if (!empty($params[$attr])) {
$value = $params[$attr];
// Check if attribute already exists in the SVG
if (preg_match('/' . preg_quote($attr) . '="[^"]*"/', $svg_content)) {
// Replace existing attribute
$svg_content = preg_replace(
'/' . preg_quote($attr) . '="[^"]*"/',
$attr . '="' . $value . '"',
$svg_content
);
} else {
// Add new attribute to the opening <svg> tag
$svg_content = preg_replace(
'/(<svg[^>]*?)>/',
'$1 ' . $attr . '="' . $value . '">',
$svg_content,
1 // Only replace the first occurrence
);
}
/* Define an associative array of SVG properties
If the property is a style, addd it in a style tag.
If the property is an attribute, replace it in the svg code.
This reduces the risk of interfering with other attributes. */
$svg_props = array(
'width' => 'style',
'height' => 'style',
'opacity' => 'style',
'fill' => 'attribute',
'stroke' => 'attribute',
);
// Styles
$styles = [];
foreach ($svg_props as $prop => $type) {
if ($type === 'style' && !empty($params[$prop])) {
$value = $params[$prop];
if (in_array($prop, ['width', 'height']) && is_numeric($value)) {
$value .= 'px';
}
$styles[] = $prop . ': ' . $value;
}
}
if (!empty($styles)) {
$style_attr = 'style="' . implode('; ', $styles) . '"';
$svg_content = preg_replace('/(<svg[^>]*?)>/', '$1 ' . $style_attr . '>', $svg_content, 1);
}
// Attributes
foreach ($svg_props as $prop => $type) {
if ($type === 'attribute' && !empty($params[$prop])) {
$value = $params[$prop];
// Use word boundaries to avoid matching partial names like fill-opacity or stroke-width
// Replace ALL occurrences of the attribute
$svg_content = preg_replace(
'/\b' . preg_quote($prop) . '\b\s*=\s*"[^"]*"/',
$prop . '="' . $value . '"',
$svg_content
);
}
}
return $svg_content;
}