<?php
namespace SabaiApps\Directories\Helper;

use SabaiApps\Directories\Application;
use SabaiApps\Directories\Component\AbstractComponent;

/**
 * ComponentEventsHelper class for retrieving event handler methods from a component.
 * Returns a list of event names handled by the component, including custom events.
 */
class ComponentEventsHelper {

	/**
	 * Gets the list of event handler methods for a component.
	 *
	 * @param Application       $app
	 * @param AbstractComponent $component
	 * @return array
	 */
	public function help( Application $app, AbstractComponent $component ) {
		// Fetch method names that start with 'on'
		$events = array_map(
			function ( $method ) {
				return strtolower( substr( $method, 2 ) );
			},
			array_filter(
				get_class_methods( $component ),
				function ( $method ) {
					return strpos( strtolower( $method ), 'on' ) === 0;
				}
			)
		);
		if ( is_callable( array( $component_class = get_class( $component ), 'events' ) )
			&& ( $_events = call_user_func( array( $component_class, 'events' ) ) ) // check for extra events
		) {
			foreach ( $_events as $event_name => $event_priority ) {
				$event_name = strtolower( $event_name );
				if ( false !== $index = array_search( $event_name, $events ) ) {
					unset( $events[ $index ] );
				}
				$events[] = array( $event_name, $event_priority );
			}
		}

		return $events;
	}
}
