<?php

namespace TotalTheme\Helpers;

defined( 'ABSPATH' ) || exit;

/**
 * SVG Sanitizer.
 */
class SVG_Sanitizer {

	/**
	 * Constructor.
	 */
	public function __construct() {}

	/**
	 * Sanitize potentially dirty SVG.
	 */
	public function sanitize( $dirty ): string {
        $dirty = preg_replace( '/<\?(=|php)(.+?)\?>/i', '', (string) $dirty ); // strip php tags.
		return (string) wp_kses( $dirty, $this->get_allowed_html() );
	}

	/**
	 * Returns array of allowed html.
	 */
	private function get_allowed_html(): array {
		$allowed_html = [
			'svg' => [
				'aria-hidden' => [],
				'aria-labelledby' => [],
				'class' => [],
				'height' => [],
				'width' => [],
				'viewbox' => [],
				'viewBox' => [],
				'role' => [],
				'xmlns' => [],
				'preserveaspectratio' => [],
				'fill' => [],
				'focusable' => [],
				'stroke' => [],
				'stroke-linecap' => [],
				'stroke-linejoin' => [],
				'stroke-width' => [],
			],
			'g' => [
				'fill'            => [],
				'fill-rule'       => [],
				'stroke'          => [],
				'stroke-linejoin' => [],
				'stroke-width'    => [],
				'stroke-linecap'  => [],
			],
			'title' => [
				'title' => [],
			],
			'path' => [
				'd'               => [],
				'fill'            => [],
				'stroke'          => [],
				'stroke-linejoin' => [],
				'stroke-width'    => [],
				'stroke-linecap'  => [],
			],
			'polyline' => [
				'points' => [],
			],
			'rect' => [
				'width'  => [],
				'height' => [],
				'x'      => [],
				'y'      => [],
				'rx'     => [],
				'ry'     => [],
			],
			'circle' => [
				'cx'     => [],
				'cy'     => [],
				'r'      => [],
			],
			'defs' => [],
			'linearGradient' => [
				'id'            => [],
				'x1'            => [],
				'y1'            => [],
				'x2'            => [],
				'y2'            => [],
				'gradientUnits' => [],
			],
			'stop' => [
				'offset'       => [],
				'stop-color'   => [],
				'stop-opacity' => [],
			],
			'polygon' => [
				'points' => [],
				'fill'   => [],
				'stroke' => [],
			],
			'line' => [
				'x1'     => [],
				'y1'     => [],
				'x2'     => [],
				'y2'     => [],
				'stroke' => [],
			],
			'ellipse' => [
				'cx' => [],
				'cy' => [],
				'rx' => [],
				'ry' => [],
			],
		];
		return apply_filters( 'totaltheme/helpers/svg_sanitizer/allowed_html', $allowed_html );
	}

}
