<?php
/**
 * Hydrate-step extension registry.
 *
 * @package EntryFoundry
 */

namespace EntryFoundry\Core\Services\Extension;

// phpcs:disable Squiz.Commenting, Generic.Commenting.DocComment

final class HydrateStepRegistry {
	/** @var array<string, array{callback:callable,priority:int}> */
	private $steps = array();

	public function register( string $name, callable $callback, int $priority = 10 ): void {
		$this->steps[ preg_replace( '/[^a-z0-9_-]/', '', strtolower( $name ) ) ] = array(
			'callback' => $callback,
			'priority' => $priority,
		);
	}

	/** @param array<string,mixed> $template @param array<string,mixed> $context @return array<string,mixed> */
	public function apply( array $template, array $context ): array {
		uasort(
			$this->steps,
			static function ( $a, $b ) {
				return $a['priority'] <=> $b['priority'];
			}
		);
		foreach ( $this->steps as $step ) {
			$template = call_user_func( $step['callback'], $template, $context );
		}
		return $template;
	}

	/** @return string[] */
	public function all(): array {
		return array_keys( $this->steps ); }
}
