| 1 |
<?php |
| 2 |
|
| 3 |
namespace StoreEngine\Utils; |
| 4 |
|
| 5 |
class Attributes { |
| 6 |
private $attributes = []; |
| 7 |
|
| 8 |
public function add_attribute( $element, $key = null, $value = null, $overwrite = false ) { |
| 9 |
if ( is_array( $element ) && is_null( $key ) && is_null( $value ) ) { |
| 10 |
// If the first argument is an array, assume it's an associative array of attributes. |
| 11 |
foreach ( $element as $attrKey => $attrValue ) { |
| 12 |
$this->add_attribute( $attrKey, $attrValue, null, $overwrite ); |
| 13 |
} |
| 14 |
} else { |
| 15 |
// If the first argument is a string, assume it's the element name. |
| 16 |
if ( ! isset( $this->attributes[ $element ] ) || $overwrite ) { |
| 17 |
if ( is_array( $key ) ) { |
| 18 |
// If $key is an array, assume it's an associative array of attributes. |
| 19 |
$this->attributes[ $element ] = array_merge( $this->attributes[ $element ] ?? [], $key ); |
| 20 |
} else { |
| 21 |
// If $key is a string, assume it's a single attribute. |
| 22 |
$this->attributes[ $element ][ $key ] = $value; |
| 23 |
} |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
return $this; |
| 28 |
} |
| 29 |
|
| 30 |
public function get_attribute_string( $element ) { |
| 31 |
$attributes = $this->attributes[ $element ] ?? []; |
| 32 |
|
| 33 |
$attributeString = ''; |
| 34 |
foreach ( $attributes as $key => $value ) { |
| 35 |
$attributeString .= sprintf( ' %s="%s"', esc_attr( $key ), esc_attr( $value ) ); |
| 36 |
} |
| 37 |
return $attributeString; |
| 38 |
} |
| 39 |
} |
| 40 |
|