<?php
namespace SabaiApps\Directories\Helper;

use SabaiApps\Directories\Application;

/**
 * FilterHelper class for applying filters to values via events.
 * Triggers a filter event and allows listeners to modify the value.
 */
class FilterHelper {

	/**
	 * Applies a filter event to a value.
	 *
	 * @param Application $application
	 * @param string      $name Filter name.
	 * @param mixed       $value Value to filter.
	 * @param array       $args Additional arguments.
	 * @return mixed
	 */
	public function help( Application $application, $name, $value = null, array $args = array() ) {
		$event_type = str_replace( '_', '', $name ) . 'filter';
		if ( $application->hasEventListner( $event_type ) ) {
			if ( is_object( $value ) ) {
				array_unshift( $args, $value );
			} else {
				// Pass in the value as reference so it can be altered
				$value_in_array = array( &$value );
				$args           = array_merge( $value_in_array, $args );
			}
			// Dispatch filter event
			$application->dispatchEvent( $event_type, $args );
		}

		return $value; // return the altered value
	}
}
