Svg.php
57 lines
| 1 | <?php |
| 2 | |
| 3 | namespace SureCart\Svg; |
| 4 | |
| 5 | class Svg { |
| 6 | /** |
| 7 | * Get the SVG file contents. |
| 8 | * |
| 9 | * @param string $filename |
| 10 | * @param array $attributes |
| 11 | * |
| 12 | * @return string SVG file contents |
| 13 | */ |
| 14 | public function get( $filename, $attributes = array() ): string { |
| 15 | $plugin_dir = SURECART_DIST_DIR . '/icon-assets'; |
| 16 | $file_path = $plugin_dir . '/' . $filename . '.svg'; |
| 17 | |
| 18 | if ( ! file_exists( $file_path ) ) { |
| 19 | return ''; |
| 20 | } |
| 21 | |
| 22 | $svg = file_get_contents( $file_path ); |
| 23 | |
| 24 | // Initialize the SVG tag processor. |
| 25 | $update_svg = new \WP_HTML_Tag_Processor( $svg ); |
| 26 | $update_svg->next_tag( 'svg' ); |
| 27 | |
| 28 | // If there are attributes to add, add them. |
| 29 | if ( ! empty( $attributes ) ) { |
| 30 | foreach ( $attributes as $attribute => $value ) { |
| 31 | // If the attribute is 'class', add the class to the SVG file without overwriting the existing classes. |
| 32 | if ( 'class' === $attribute ) { |
| 33 | $update_svg->add_class( $value ); |
| 34 | continue; |
| 35 | } |
| 36 | |
| 37 | // If the attribute is 'style', append the style to the SVG file without overwriting the existing styles. |
| 38 | if ( 'style' === $attribute ) { |
| 39 | $existingStyle = $update_svg->get_attribute( 'style' ); |
| 40 | $value = $existingStyle ? $existingStyle . '; ' . $value : $value; |
| 41 | } |
| 42 | |
| 43 | // Otherwise, set/update the attribute with the new value |
| 44 | $update_svg->set_attribute( $attribute, $value ); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // Add the 'pointer-events: none;' style to make the SVG non-interactive. |
| 49 | $existingStyle = $update_svg->get_attribute( 'style' ); |
| 50 | $newStyle = $existingStyle ? $existingStyle . '; pointer-events: none;' : 'pointer-events: none;'; |
| 51 | $update_svg->set_attribute( 'style', $newStyle ); |
| 52 | |
| 53 | // Return the updated SVG string. |
| 54 | return $update_svg->get_updated_html(); |
| 55 | } |
| 56 | } |
| 57 |