<?php

namespace Entity;

class Meta extends ModelBase
{
    private $entity;

    protected function install()
    {
        $dbPrefix = $this->getDbPrefix();
        $result = self::$dbo->exec("CREATE TABLE IF NOT EXISTS `{$dbPrefix}meta` (
            `entity_id` INTEGER(11) UNSIGNED NOT NULL,
            `entityType` VARCHAR(32) NOT NULL,
            `lang` VARCHAR(8) NULL,
            `key` VARCHAR(64) NOT NULL,
            `value` TEXT NULL,
            UNIQUE(`entity_id`, `entityType`, `lang`)
        )");
        if ($result === false)
            throw new \Exception(get_class().": ".self::$dbo->errorInfo()[2]);
        return true;
    }

    public function __get($key)
    {
        if ($key == "entity")
            return $this->entity;
        return parent::__get($key);
    }

    public function __set($key, $value)
    {
        if ($key == "entity")
        {
            parent::__set("entityId", $value->id);
            parent::__set("entityType", get_class($value));
            return $value;
        }
        else if ($key == "entityId" || $key == "entityType")
            throw new \Exception("Cannot access private field {$key}");
        return parent::__set($key, $value);
    }
}

