<?php
/**
 * PHP 7.4-compatible backed-enum value validation.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChanges\Support;

// phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Exception messages are escaped at UI boundaries.

/**
 * Validates string values against constant-list classes.
 */
final class EnumValue {
	/**
	 * Returns a valid value or throws.
	 *
	 * @param class-string $enum_class Constant-list class.
	 * @param string       $value Value to validate.
	 */
	public static function from( string $enum_class, string $value ): string {
		$resolved = self::tryFrom( $enum_class, $value );

		if ( null === $resolved ) {
			throw new \InvalidArgumentException(
				sprintf( 'Invalid value "%s" for %s.', $value, $enum_class )
			);
		}

		return $resolved;
	}

	/**
	 * Returns a valid value or null.
	 *
	 * @param class-string $enum_class Constant-list class.
	 * @param string       $value Value to validate.
	 */
	public static function tryFrom( string $enum_class, string $value ): ?string {
		if ( ! class_exists( $enum_class ) ) {
			return null;
		}

		$values = ( new \ReflectionClass( $enum_class ) )->getConstants();

		return in_array( $value, $values, true ) ? $value : null;
	}
}
