<?php
/**
 * Svg Helper functions.
 *
 * @since 2.6.8
 * @package Masteriyo\Addons\PublicProfile
 */

namespace Masteriyo\Addons\PublicProfile;

defined( 'ABSPATH' ) || exit;


use Masteriyo\Constants;

class Svg {

	/**
	 * Return or echo public profile svg icon.
	 *
	 * @since 2.6.8
	 *
	 * @param string $name
	 * @return string
	 */
	public static function get( $name, $echo = false ) {
		global $wp_filesystem;

		$credentials = request_filesystem_credentials( '', 'direct' );

		// Bail early if the credentials is wrong.
		if ( ! $credentials ) {
			return;
		}

		\WP_Filesystem( $credentials );

		$file_name     = Constants::get( 'MASTERIYO_PUBLIC_PROFILE_ADDON_DIR' ) . "/assets/svgs/{$name}.svg";
		$file_contents = '';

		if ( file_exists( $file_name ) && is_readable( $file_name ) ) {
			$file_contents = $wp_filesystem->get_contents( $file_name );
		}

		/**
		 * Filters svg file content.
		 *
		 * @since 2.6.8
		 *
		 * @param string $file_content SVG file content.
		 * @param string $name SVG file name.
		 */
		$file_contents = apply_filters( 'masteriyo_public_profile_svg_icon', $file_contents, $name );

		$svg_args = array(
			'svg'      => array(
				'class'           => true,
				'aria-hidden'     => true,
				'aria-labelledby' => true,
				'role'            => true,
				'xmlns'           => true,
				'width'           => true,
				'height'          => true,
				'viewbox'         => true, // <= Must be lower case!
				'fill'            => true,
			),
			'g'        => array(
				'fill'      => true,
				'clip-path' => true,
			),
			'title'    => array( 'title' => true ),
			'defs'     => array(),
			'clipPath' => array( 'id' => true ),
			'path'     => array(
				'd'    => true,
				'fill' => true,
			),
		);

		if ( $echo ) {
			echo wp_kses( $file_contents, $svg_args );
		} else {
			return $file_contents;
		}
	}
}
