<?php
/**
 * Class represents records from table translations
 * {autogenerated}
 * @property string $language PK
 * @property string $translations
 * {/autogenerated}
 */
class Translation extends Am_Record
{
    protected $_key = 'trans_id';
    protected $_table = '?_translation';
}

/** @extends Am_Table<Translation> */
class TranslationTable extends Am_Table
{
    protected $_key = 'trans_id';
    protected $_table = '?_translation';
    protected $_recordClass = 'Translation';

    function getTranslationData($locale)
    {
        return $this->getDi()->cacheFunction->call(function($locale) {
            $translations = $this->_db->selectCell("SELECT translations FROM ?_translation WHERE language = ?", $locale);
            return $translations ? unserialize($translations) : [];
        }, [$locale], ['id' => 'translations_' . $locale]);
    }

    function replaceTranslation($translations, $locale)
    {
        $prevTranslations = (array)$this->getTranslationData($locale);
        $newTranslations = array_merge($prevTranslations, $translations);
        $sql = "REPLACE ?_translation SET translations = ?, language = ?";
        $this->_db->query($sql, serialize($newTranslations), $locale);
        $this->getDi()->cacheFunction->remove('translations_' . $locale);
    }
}