<?php

namespace FCA\StockApi\Document;

use FCA\StockApi\Exception\ApiException;

abstract class Base
{
    /**
     * @param $requiredKeys
     * @param $inputData
     * @throws ApiException
     */
    protected function checkKeys($requiredKeys, $inputData)
    {
        foreach ($requiredKeys as $key) {
            if (!array_key_exists($key, $inputData)) {
                throw new ApiException('Key: "' . $key . '" is undefined!"');
            }
        }
    }

    /**
     * @return array
     */
    public function toArray()
    {
        $vars = [];

        try {
            $reflect = new \ReflectionClass(get_class($this));
            $vars   = $reflect->getProperties(\ReflectionProperty::IS_PROTECTED);
        } catch (\ReflectionException $e) {
            // Ten wyjątek nie powinien zostać wyrzucony (klasa która wywołuje tą metodę musi istnieć)
        }

        $array = [];
        foreach ($vars as $key) {
            if (is_array($this->{$key->name})) {
                $array[$key->name] = [];
                foreach ($this->{$key->name} as $item) {
                    if (is_object($item)) {
                        $array[$key->name][] = $item->toArray();
                    } else {
                        $array[$key->name][] = $item;
                    }
                }
            } elseif (is_object($this->{$key->name})) {
                $array[$key->name] = $this->{$key->name}->toArray();
            } else {
                $array[$key->name] = $this->{$key->name};
            }
        }

        return $array;
    }
}
