Skip to content

Instantly share code, notes, and snippets.

@tappleby
Forked from burlresearch/TranslatableTrait.php
Created April 15, 2015 00:55
Show Gist options
  • Save tappleby/cdc447819f6168dc1df3 to your computer and use it in GitHub Desktop.
Save tappleby/cdc447819f6168dc1df3 to your computer and use it in GitHub Desktop.
<?php
/*
* (C) Copyright 2015 76design Inc (https://76design.com) and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @created:2015.04.14
* @author: appleby
* Contributors:
* ...
*/
namespace Scc\Eloquent;
use Lang;
/**
* Used for translating attributes.
*
* Usage:
*
* class Model extends Eloquent {
* use TranslatableTrait;
*
* protected $translatable = ['title'];
* }
*
* @package Scc\Eloquent
*/
trait TranslatableTrait {
public function getAttribute($key) {
$locale_attr = $this->getLocaleAttributeKeye($key);
$isTranslatable = !empty($this->translatable) && in_array($key, $this->translatable);
if ($isTranslatable && array_key_exists($locale_attr, $this->attributes) && ($attr = $this->getAttributeValue($locale_attr))) {
return $attr;
}
return parent::getAttribute($key);
}
public function attributesToArray() {
$attributes = parent::attributesToArray();
$translatable = (array)$this->translatable;
foreach ($translatable as $key) {
$locale_attr = $this->getLocaleAttributeKey($key);
if (!empty($attributes[$locale_attr])) {
$attributes[$key] = $attributes[$locale_attr];
}
}
return $attributes;
}
protected function getLocaleAttributeKey($key) {
return $key . '_' . Lang::getLocale();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment