/**
  * Handle 'afterFind' event of the owner.
  */
 public function afterFind()
 {
     if ($this->owner->isRelationPopulated('translations') && ($related = $this->owner->getRelatedRecords()['translations'])) {
         $translations = $this->indexByLanguage($related);
         foreach ($this->availableLanguages as $lang) {
             foreach ($this->attributes as $attribute) {
                 foreach ($translations as $translation) {
                     if ($translation->{$this->languageField} == $lang) {
                         $this->setTranslateAttribute($attribute . '_' . $lang, $translation->{$attribute});
                         if ($lang == Yii::$app->language) {
                             $this->setTranslateAttribute($attribute, $translation->{$attribute});
                         }
                     }
                 }
             }
         }
     } else {
         if (!$this->owner->isRelationPopulated('translation')) {
             $this->owner->translation;
         }
         $translation = $this->owner->getRelatedRecords()['translation'];
         if ($translation) {
             foreach ($this->attributes as $attribute) {
                 $this->owner->setTranslateAttribute($attribute, $translation->{$attribute});
             }
         }
     }
     foreach ($this->attributes as $attribute) {
         if ($this->owner->hasAttribute($attribute) && $this->getTranslateAttribute($attribute)) {
             $this->owner->setAttribute($attribute, $this->getTranslateAttribute($attribute));
         }
     }
 }
Esempio n. 2
0
 /**
  * Get an array representing the properties of a model.
  *
  * @param \yii\db\ActiveRecord $model
  * @return array
  */
 public static function castModel(ActiveRecord $model)
 {
     $attributes = array_merge($model->getAttributes(), $model->getRelatedRecords());
     $results = [];
     foreach ($attributes as $key => $value) {
         $results[Caster::PREFIX_VIRTUAL . $key] = $value;
     }
     return $results;
 }