<?php

namespace system\entity;

/**
 * Class EntityClass contém os metodos obrigatorios para todas as entitys com ligação a base de dados
 * @package system\entity
 */
abstract class EntityClass implements \JsonSerializable
{

    abstract protected function getTableId();

    /**
     * @return array
     */
    public function __toArray()
    {

        $obejectVars = array();
        $reflection = new \ReflectionClass(get_class($this));
        foreach ($reflection->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED) as $property) {
            $property->setAccessible(true);
            $obejectVars[$property->getName()] = $property->getValue($this);
        }

        return [
            'obejectVars' => $obejectVars,
            'entityFields' => array_keys($obejectVars),
            'entityValues' => array_values($obejectVars),
            'entityIndex' => array_key_first($obejectVars)
        ];

    }

    /**
     * Ao usar a função jsonEncode em classes herdadas ira usar a função abaixo para pegar todos as propriedades
     * sendo elas publicas/privadas/protected
     *
     * @return array|mixed
     * @throws \ReflectionException
     */
    public function jsonSerialize(): mixed
    {
        $public = [];
        $reflection = new \ReflectionClass(get_class($this));
        foreach ($reflection->getProperties() as $property) {
            $property->setAccessible(true);
            $public[$property->getName()] = $property->getValue($this);
        }
        return $public;
    }

    /**
     * Retorna todas as propriedades da classe que não seja protected
     *
     * @return array
     * @throws \ReflectionException
     */
    public function getClassWithOutProtected()
    {
        $public = [];
        $reflection = new \ReflectionClass(get_class($this));
        foreach ($reflection->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PRIVATE) as $property) {
            $property->setAccessible(true);
            $public[$property->getName()] = $property->getValue($this);
        }
        return $public;
    }

}