Seo.php 1.5 KB
<?php
namespace frontend\widgets;
use common\models\SeoCategory;
use common\models\SeoDynamic;
use yii\base\Widget;
use yii\helpers\Html;

class Seo extends Widget
{
    private $url;
    public  $row;
    public  $own_attr;
    public  $fields;

    public function init(){
        $this->url   = $_SERVER['REQUEST_URI'];
        parent::init();

    }


    public function run()
    {
        $row = '';


        $widgetData = $this->findSeoByUrl();
        if($widgetData instanceof \common\models\Seo){

            $row =  $widgetData->{$this->row};
        } else{

            $widgetData = $this->findSeoByDynamic();
            if($widgetData instanceof SeoDynamic){
                $row =  $widgetData->{$this->row};
            }
        }
        if(!empty($this->own_attr) && empty($row)) {

            $row = $this->own_attr;
        }


        return $this->replaceData($row);


    }

    protected function replaceData($str)
    {

        if(!empty($this->fields)){
            foreach($this->fields as $field_name => $field_value){
                $str = str_replace('{'.$field_name.'}', $field_value, $str);
            }
        }
        return Html::encode($str);
    }

    protected function findSeoByUrl()
    {
        return  \common\models\Seo::findOne(['url'=>$this->url]);
    }

    protected function findSeoByDynamic()
    {
        return SeoDynamic::find()->joinWith('seoCategory')->where(['controller'=> \Yii::$app->controller->id, 'action'=>\Yii::$app->controller->action->id])->one();
    }
}