LanguageWidget.php 5.87 KB
<?php
    
    namespace frontend\widgets;
    
    use artbox\core\models\Alias;
    use artbox\core\services\Languages;
    use yii\base\Widget;



    //==============================================================================================================
    //
    //Виджет может принимать на вход информацию о том,
    // 1) какой шаблон вывести в конце
    //  -- LAYOUT_DEFAULT   ==> выведутся только линки : <a href='..............
    //  -- LAYOUT_LI        ==> выведутся линки внутри li
    //  -- LAYOUT_UL        ==> выведется полноценный список
    //
    //Дополнительно можно передать параметры для a/li/ul (class) через $layoutAttributes в виде:
    //
    //  LanguageWidget([
    //                     "layoutCondition"=>LanguageWidget::LAYOUT_UL,
    //                      "layoutAttributes" =>
    //                              [ "ul" =>
    //                                        [
    //                                          "class" => "myClassName",
    //                                          ]
    //                                ]
    //
    //==============================================================================================================
    class LanguageWidget extends Widget
    {

    	const LAYOUT_UL='ul';
    	const LAYOUT_LI='li';
    	const LAYOUT_DEFAULT='default';

    	public $layoutCondition=null;
	    public $layoutAttributes=[];


        /**
         * @var \artbox\core\components\SeoComponent
         */
        protected $seo;
        
        /**
         * @var \artbox\core\services\Languages
         */
        protected $languages;


        /**
         * @var array
         */
        protected $links = [];


    
        /**
         * LanguageWidget constructor.
         *
         * @param \artbox\core\services\Languages $languages
         * @param array                           $config
         *
         * @throws \yii\base\InvalidConfigException
         * @throws \yii\di\NotInstantiableException
         */
        public function __construct(Languages $languages, array $config = [])
        {
            $this->languages = $languages;
    
            $this->seo = \Yii::$container->get('artbox\core\components\SeoComponent');
            
            parent::__construct($config);
        }
        
        public function init()
        {
            parent::init();

            if ($this->seo->loaded) {
                $currentAlias = Alias::findOne($this->seo->getAliasId());
                
                $aliases = Alias::find()
                                ->where(
                                    [
                                        'route' => $currentAlias->route,
                                    ]
                                )
                                ->indexBy('language_id')
                                ->all();
                
                /**
                 * @var Alias[] $aliases
                 */
                foreach ($aliases as $alias) {
                    if ($alias->id === $this->seo->getAliasId()) {
                        $active = true;
                    } else {
                        $active = false;
                    }
                    
                    if (( $alias->language_id === $this->languages->getDefault(
                            )->id ) && \Yii::$app->urlManager->hideDefaultLanguagePrefix) {
                        $url = '/' . $alias->value;
                    } else {
                        $url = '/' . $this->languages->getUrlById($alias->language_id) . '/' . $alias->value;
                    }
                    
                    $this->links[] = [
                        'active' => $active,
                        'url'    => $url,
                        'title'  => $this->languages->getUrlById($alias->id),
                    ];
                }
            } else {
                $languages = $this->languages->getActive();
                
                foreach ($languages as $language) {
                    if ($language->id === $this->languages->getCurrent()->id) {
                        $active = true;
                    } else {
                        $active = false;
                    }
                    
                    if (( $language->id === $this->languages->getDefault(
                            )->id ) && \Yii::$app->urlManager->hideDefaultLanguagePrefix) {
                        $prefix = '';
                    } else {
                        $prefix = '/' . $language->url;
                    }
                    
                    $url = $prefix . '/' . \Yii::$app->request->pathInfo;
                    
                    $this->links[] = [
                        'active' => $active,
                        'url'    => $url,
                        'title'  => $language->url,
                    ];
                }
            }

			foreach ($this->links as &$link){
				if($link['title']=='ru') {
					$link['title']=($language::getCurrent()->url=='ru')?'рус':'рос';
				}
				elseif($link['title']=='ua')$link['title']='укр';
			}

            # определяем, какой же из шаблонов нам нужен
	        if(!isset($this->layoutCondition)
		        || !in_array($this->layoutCondition,[self::LAYOUT_DEFAULT,self::LAYOUT_LI,self::LAYOUT_UL])
	        )$this->layoutCondition=self::LAYOUT_DEFAULT;





        }
        
        public function run()
        {
            return $this->render(
                '_languages',
                [
                    'links'             => $this->links,
	                'layoutCondition'   => $this->layoutCondition,
	                'layoutAttributes'  => $this->layoutAttributes,
                ]
            );
        }
    }