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 acddbd97d7

View File

@ -212,14 +212,9 @@ class SmartyHelperFunctions
{svg_icon file='person.svg'} {svg_icon file='person.svg'}
*/ */
if (empty($params['file'])) { // Grab svg under falcon/_dev/img and display an error if not found
return ''; $icon_path = _PS_THEME_DIR_ . '/_dev/img/' . 'svg';
}
// 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 (!is_file($icon_path)) {
if (defined('_PS_MODE_DEV_') && _PS_MODE_DEV_) { if (defined('_PS_MODE_DEV_') && _PS_MODE_DEV_) {
return 'Invalid SVG path: ' . htmlspecialchars($icon_path); return 'Invalid SVG path: ' . htmlspecialchars($icon_path);
@ -229,40 +224,49 @@ class SmartyHelperFunctions
$svg_content = file_get_contents($icon_path); $svg_content = file_get_contents($icon_path);
// Define SVG attributes that should be replaced/added /* Define an associative array of SVG properties
$svg_attributes = [ If the property is a style, addd it in a style tag.
'width', If the property is an attribute, replace it in the svg code.
'height',
'fill',
'stroke',
'stroke-width',
'opacity',
'viewBox',
];
foreach ($svg_attributes as $attr) { This reduces the risk of interfering with other attributes. */
if (!empty($params[$attr])) { $svg_props = array(
$value = $params[$attr]; 'width' => 'style',
'height' => 'style',
'opacity' => 'style',
'fill' => 'attribute',
'stroke' => 'attribute',
);
// Check if attribute already exists in the SVG // Styles
if (preg_match('/' . preg_quote($attr) . '="[^"]*"/', $svg_content)) { $styles = [];
// Replace existing attribute 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( $svg_content = preg_replace(
'/' . preg_quote($attr) . '="[^"]*"/', '/\b' . preg_quote($prop) . '\b\s*=\s*"[^"]*"/',
$attr . '="' . $value . '"', $prop . '="' . $value . '"',
$svg_content $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
);
}
} }
} }
return $svg_content; return $svg_content;
} }