Termin.php 5.65 KB
<?php

namespace common\models;

use Yii;
use common\models\SqlQueryBuilder;

/**
 * This is the model class for table "termin".
 *
 * @property integer $termin_id
 * @property integer $termin_type_id
 * @property integer $page_id
 */
class Termin extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'termin';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['termin_type_id', 'page_id'], 'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'termin_id' => 'Termin ID',
            'termin_type_id' => 'Termin Type ID',
            'page_id' => 'Page ID',
        ];
    }
    
    // ======================
    // ==== MY CASTYL :D ====
    // ======================
    
    // ==== Common ====

    /**
     * находит термин и перевод (не учитывает таблицу relation)
     * @param array $array
     * @return array
     */
    static function findTemin (array $array)
    {
        Tools::ifNotExist ($array, [
            'return_one' => true,
        ]);

        $query = new SqlQueryBuilder();
        $query->from('termin_lang');
        $query->innerJoin(
            'termin', NULL, '
            `termin`.termin_id = `termin_lang`.termin_id
                AND `termin`.type = "'.$array['type'].'"
        ');
    
        if (isset ($array['lang_id']))
        {
            $query->where('`termin_lang`.lang_id = '.(int)$array['lang_id']);
        }
    
        if (isset ($array['termin_title']))
        {
            $query->where('`termin_lang`.termin_title = "'.$array['termin_title'].'"');
        }

        // sql
        $result = yii::$app->db->createCommand($query->__toString());
    
        return $array['return_one'] !== false ? $result->queryOne() : $result->queryAll();
    }

    /**
     * Создает термин, перевод и связь
     * @param array $array
     * @return int termin_id
     */
    static function add (array $array)
    { 
        // термин
        $array['termin_id'] = self::addTermin ($array);
 
        // термин перевод
        self::addTerminLang ($array);

        // связи
        self::addTerminRelation ($array);
        
        return $array['termin_id'];
    }
    
    /**
     * Ищет и добавляет того чего нет (термин, перевод, relation) <br/>
     * В сновном заточен под импорт
     * @param array $basic
     * @return int termin_id
     */
    static function addIfNotExists (array $basic)
    {      
        $termin_id = 0;

        // категория
        $termin = Termin::findTemin ($basic);
        if (! empty ($termin))
        {
            // массив связи
            $add = [
                'termin_id' => $termin['termin_id'],
                'termin_pid' => $basic['termin_pid'],
            ];

            // есть ли связь
            $relation = Termin::findRelation ($add);
            if (empty ($relation))
            {
                // добавляем
                Termin::addTerminRelation ($add);
            }
 
            $termin_id = $termin['termin_id'];
        }
        else
        {
            // добавляем
            $termin_id = Termin::add ($basic);
        }

        return $termin_id;
    }

    // ==== Termin ===

    static function addTermin (array $array)
    {
        Tools::ifNotExist ($array, [
            'type' => 'H',
            'page_id' => 0, 
        ]);
 
        Yii::$app->db->createCommand()->insert(
            'termin', [
                'type' => $array['type'],
                'page_id' => (int)$array['page_id'],
            ]        
        )->execute();
            
        return Yii::$app->db->getLastInsertID();
    }

    // ==== Termin Lang ====

    static function addTerminLang (array $array)
    {
        Tools::ifNotExist ($array, [
            'template_id' => 0,
            'termin_alias' => strtolower (Tools::translit ($array['termin_title'])),
        ]);

        Yii::$app->db->createCommand()->insert(
            'termin_lang', [
                'termin_id' => $array['termin_id'],
                'termin_title' => $array['termin_title'],
                'termin_alias' => $array['termin_alias'],
                'template_id' => (int)$array['template_id'],
                'lang_id' => (int)$array['lang_id'],
            ]        
        )->execute(); 
    }

    // ==== Termin Relation ====

    static function findRelation (array $array)
    {
        $query = new SqlQueryBuilder();
        $query->from('termin_relation');
    
        if (isset ($array['termin_id']))
        {
            $query->where('termin_id = "'.$array['termin_id'].'"');
        }

        if (isset ($array['termin_pid']))
        {
            $query->where('termin_pid = "'.$array['termin_pid'].'"');
        }

        // sql
        $result = yii::$app->db->createCommand($query->__toString());
    
        return isset ($array['return_one']) ? $result->queryOne() : $result->queryAll();
    }

    static function addTerminRelation (array $array)
    {
        Tools::ifNotExist ($array, [
            'termin_pid' => 0,
            'is_default' => 1,
        ]);

        Yii::$app->db->createCommand()->insert(
            'termin_relation', [
                'termin_id' => (int)$array['termin_id'],
                'termin_pid' => (int)$array['termin_pid'],
                'is_default' => (int)$array['is_default'], 
            ]
        )->execute();
            
        return Yii::$app->db->getLastInsertID();
    }
}