<?php

declare(strict_types=1);

namespace ComerciaGlobalPayments\AddonPayments\SDK\_3DSecure\v2;

use ReflectionClass;
use ReflectionProperty;

/**
 * Class AbstractSchemaObject.
 *
 * Base class for schema objects.
 *
 * @todo Consider using Symfony Validation component https://symfony.com/doc/3.4/validation.html
 */
abstract class AbstractSchemaObject implements SchemaObjectInterface, \JsonSerializable
{
    /**
     * AbstractSchemaObject constructor.
     */
    public function __construct(array $data = [])
    {
        foreach ($this->getDefaults() as $property => $value) {
            $method = 'set'.ucfirst($property);
            if (method_exists($this, $method)) {
                $this->$method($data[$property] ?? $value);
            }
        }
    }

    public function jsonSerialize(): array
    {
        $reflection = new ReflectionClass($this);
        $properties = $reflection->getProperties(ReflectionProperty::IS_PRIVATE);
        $data = [];

        foreach ($properties as $property) {
            $name = $property->getName();
            $data[$name] = $this->{'get' . ucfirst($name)}();
        }

        return $data;
    }
}
