<?php
/**
 * Created by PhpStorm.
 * Damian Banaszkiewicz <dbanaszkiewicz@unicorn.net.pl>
 * 23.08.18 08:56
 */

namespace FCA\StockApi\Document;

use FCA\StockApi\Exception\ApiException;

abstract class Base
{
    /**
     * @param $required_keys
     * @param $inputData
     * @throws ApiException
     */
    protected function checkKeys($required_keys, $inputData)
    {
        foreach ($required_keys 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;
    }
}
