<?php
/**
 * Please see weepie-framework.php for more details.
 */

namespace WpieFw\Shortcodes;

use WpieFw\Wpie\WpieGlobals;
use WpieFw\Exceptions\WpieExceptionInterface;

if( ! defined( 'ABSPATH' ) ) exit;

/**
 * WpieShortcodes Class
 *
 * @author $Author: Vincent Weber <weepie-plugins@outlook.com> $
 * @since 1.4.0
 */
final class WpieShortcodes
{
	/**
	 * @var WpieGlobals
	 */
	private $globals;

	/**
	 * Constructor
	 *
	 * @access public
	 *
	 * @param WpieGlobals $globals
	 *
	 * @since 1.4.0
	 */
	public function __construct( WpieGlobals $globals )
	{
		$this->globals = $globals;
	}

	/**
	 * Callback for the registered shortcodes
	 *
	 * @access	public
	 *
	 * @param	array	$atts
	 * @param string 	$content
	 * @param string 	$tag
	 *
	 * @uses 	filter {nameSpace}_shortcode_{$tag} to perform the shortcode logic
	 *
	 * @since	2.3.x
	 *
	 * @return	string
	 */
	public function doshortcode( $atts = [], $content = null, $tag = '' )
	{
		try {
			/**
			 * Let others hook into the add_shortcode callback before anything is done
			 */
			do_action( $this->globals->nameSpace . '_before_shortcode_' . $tag, $atts, $content );

			/**
			 * @todo description for hook {$nameSpace}_shortcode_{$tag}
			 */
			return apply_filters( $this->globals->nameSpace . '_shortcode_' . $tag, $atts, $content, $tag );
		} catch ( WpieExceptionInterface $e ) {
			throw $e;
		}
	}

	/**
	 * Add schortcodes
	 *
	 * Plugins can add shortcodes with the hook {$nameSpace}_registered_shortcodes
	 *
	 * @access public
	 *
	 * @uses add_shortcode()
	 */
	public function add()
	{
		try {
			/**
			 * Let plugin modules add shortcodes
			 *
			 * @param array $shortcodes
			 *
			 * @since 1.2.5
			 *
			 * @return array
			 */
			$shortcodes = apply_filters( $this->globals->nameSpace . '_registered_shortcodes', [] );
		} catch( WpieExceptionInterface $e ) {
			throw $e;
		}

		if( is_array( $shortcodes ) && 0 < count( $shortcodes ) ) {
			foreach ( $shortcodes as $sc ) {
				add_shortcode( $sc, [$this, 'doshortcode'] );
			}
		}
	}
}