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

use InvalidArgumentException;
use ReflectionClass;
use ReflectionException;
use ReflectionProperty;

/**
 * Class RequiredPropertiesValidator
 * @package Fifa\ConnectId\Sdk\Util\XmlDeserializer
 */
class RequiredPropertiesValidator
{
    /**
     * @param object $instance
     * @return bool
     * @throws ReflectionException
     * @throws InvalidArgumentException
     */
    public static function validate($instance): bool
    {
        if (!is_object($instance)) {
            throw new InvalidArgumentException('Cannot validate properties of not an object.');
        }

        $class = get_class($instance);
        $reflectionInstance = new ReflectionClass($class);
        $properties = $reflectionInstance->getProperties(ReflectionProperty::IS_PUBLIC);

        foreach ($properties as $property) {
            $docComment = $property->getDocComment();
            $value = $property->getValue($instance);
            if (strpos($docComment, '@required') !== false && $value === null) {
                throw new InvalidArgumentException(sprintf('Property "%s" of object "%s" cannot be null.', $property->getName(), $class));
            }
        }

        return true;
    }
}