<?php

namespace common\modules\relation;

use Yii;
use yii\base\Object;

class relationHelper extends Object {
    /** @var array $relations Cached relations list */
    private static $relations;

    /**
     * Return all relations for current @app
     * @return array
     */
    public static function getRelations() {
        $module = \Yii::$app->getModule('relation');

        if (!is_array($module->relations))
            return [];

        return $module->relations;
    }

    /**
     * Return one relation for key $name
     * @param string $name
     * @return string (@todo refix to relationOject)
     */
    public static function getRelation($name) {
        $name = strtolower($name);
        if (isset(self::$relations[$name])) {
            return self::$relations[$name];
        }
        $relations = self::getRelations();
        if (isset($relations[$name])) {
            self::$relations[$name] = self::prepareRelation($relations[$name]);
        } else {
            self::$relations[$name] = null;
        }
        return self::$relations[$name];
    }


    private static function prepareRelation($relation) {
        if (!isset($relation['linked_table']) && isset($relation['via']['model'])) {
            $relation['linked_table'] = $relation['via']['model']::tableName();
        }
        return $relation;
    }

    /**
     * @param string $name
     * @return bool
     */
    public static function issetRelation($name) {
        $relations = self::getRelations();
        return isset($relations[$name]);
    }
}