<?php
namespace Fifa\ConnectId\Sdk\Util\Modifiers;

use DateTime;
use DirectoryIterator;
use ReflectionClass;

class Modifiers
{
    const RFC3339_Date_Modifier = 'RFC3339DateModifier';

    private static $modifiers = [];

    public static function __constructStatic()
    {
        $iterator = new DirectoryIterator(__DIR__);
        $modifiersInterfaceName = 'ModifiersInterface';
        foreach ($iterator as $file) {
            if ($file->isFile() && $file->getExtension() === 'php') {
                require_once $file->getPathname();
                $className = $file->getBasename('.php');
                $reflectionClass = new ReflectionClass(__NAMESPACE__ . '\\' . $className);

                if ($className !== $modifiersInterfaceName
                    && $reflectionClass->implementsInterface(__NAMESPACE__.'\\'.$modifiersInterfaceName)) {
                    $className = $reflectionClass->getName();
                    array_push(self::$modifiers, new $className());
                }
            }
        }
    }

    public static function resolveModifier($data, $property): ?string {
        foreach(self::$modifiers as $modifier) {
            $resolvedModifier = $modifier->resolveModifier($data, $property);
            if($resolvedModifier !== null) {
                return $resolvedModifier;
            }
        }
        return null;
    }

    public static function applyModifier($modifierName, $arg) {
        if($modifierName === self::RFC3339_Date_Modifier && $arg instanceof DateTime) {
            return $arg->format("Y-m-d\TH:i:sP");
        }
        return $arg;
    }
}

Modifiers::__constructStatic();