<?php
/**
 * License platform identifiers (marketplace of record).
 *
 * @package The7
 */

namespace The7\License;

defined( 'ABSPATH' ) || exit;

/**
 * Class License_Platform
 */
final class License_Platform {

	public const ENVATO   = 'envato';
	public const FREEMIUS = 'freemius';
	const DEFAULT_FREEMIUS_LICENSE_KEY_REGEX = '/^sk_[\x21-\x7E]{8,188}$/';
	const DEFAULT_ENVATO_LICENSE_KEY_REGEX   = '/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i';

	/**
	 * Default platform when none is stored.
	 *
	 * @return string
	 */
	public static function default() {
		return self::FREEMIUS;
	}

	/**
	 * @param string $value Platform string from storage or API.
	 *
	 * @return bool
	 */
	public static function is_known( $value ) {
		return in_array( $value, [ self::ENVATO, self::FREEMIUS ], true );
	}

	/**
	 * @param string $code
	 * @return bool
	 */
	public static function is_freemius( string $code ): bool {
		if ( strlen( $code ) !== 32 ) {
			return false;
		}

		return (bool) preg_match( self::DEFAULT_FREEMIUS_LICENSE_KEY_REGEX, $code );
	}

	/**
	 * @param  string  $code
	 *
	 * @return bool
	 */
	public static function is_envato( string $code ): bool {
		if ( strlen( $code ) !== 36 ) {
			return false;
		}

		return (bool) preg_match( self::DEFAULT_ENVATO_LICENSE_KEY_REGEX, $code );
	}
}
