<?php
namespace Newland\Toubiz\Sync\Neos\Enum;

/*
 * This file is part of the "toubiz-sync-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

class Enum
{
    /** @var array */
    protected static $constants;

    public static function throwIfInvalid($value, $exception = \InvalidArgumentException::class): void
    {
        if (static::validValue($value)) {
            return;
        }

        throw new $exception(
            sprintf(
                '%s "%s" is not valid. Valid values: %s',
                static::name(),
                (string) $value,
                implode(', ', static::values())
            )
        );
    }

    public static function name(): string
    {
        $parts = explode('\\', static::class);
        return (string) array_pop($parts);
    }

    public static function validValue($value): bool
    {
        return \in_array($value, static::values(), true);
    }

    public static function values(): array
    {
        static::extractConstants();
        return array_values(static::$constants);
    }

    /**
     * @throws \ReflectionException
     * @return void
     */
    private static function extractConstants()
    {
        if (static::$constants) {
            return;
        }

        static::$constants = (new \ReflectionClass(static::class))->getConstants();
    }
}
