<?php
namespace WAM\Bundle\CoreBundle\Model;
use Doctrine\Common\Inflector\Inflector;
use Knp\DoctrineBehaviors\Model\Translatable\Translatable as BaseTranslatable;
use Sonata\AdminBundle\Exception\NoValueException;
use Symfony\Component\PropertyAccess\Exception\AccessException;
use WAM\Component\Core\Util\StringTools;
/**
* Trait Translatable.
*
* @author Gerard Rico <grico@wearemarketing.com>
*/
trait Translatable
{
use BaseTranslatable;
/**
* Returns translation entity class name.
*
* @return string
*/
public static function getTranslationEntityClass()
{
return static::class.'Translation';
}
/**
* @param string $locale
*
* @return $this
*/
public function setLocale($locale)
{
$this->setCurrentLocale($locale);
return $this;
}
/**
* @return string
*/
public function getLocale()
{
return $this->getCurrentLocale();
}
public function getTranslation(string $locale = null)
{
return $this->translate($locale, false);
}
public function clearTranslationsExcept(array $locales)
{
foreach ($this->getTranslations() as $locale => $translation) {
if (!in_array($locale, $locales)) {
$this->removeTranslation($translation);
}
}
}
public function setTranslations($translations)
{
if (!$translations instanceof \Traversable && !is_array($translations)) {
throw new \InvalidArgumentException('$translations parameter must be iterable');
}
$this->translations->clear();
foreach ($translations as $translation) {
$this->addTranslation($translation);
}
return $this;
}
public function __get($property)
{
$translation = $this->translate(null, false);
$method = 'get'.Inflector::classify($property);
if (!method_exists($translation, $method)) {
throw new AccessException("Unable to get property $property");
}
return $translation->{$method}();
}
public function __set($property, $value)
{
$translation = $this->translate(null, false);
$method = 'set'.Inflector::classify($property);
if (!method_exists($translation, $method)) {
throw new AccessException("Unable to set property $property");
}
$translation->{$method}($value);
}
public function __call($method, $arguments)
{
$translation = $this->getTranslation();
$isSet = StringTools::startsWith($method, 'set');
if (
!method_exists($translation, $method)
and !StringTools::startsWith($method, 'get')
and !$isSet
) {
$originalMethod = $method;
$method = 'get'.Inflector::classify($method);
if (!method_exists($translation, $method)) {
throw new NoValueException(sprintf('Unable to retrieve the value of `%s`', $originalMethod));
}
}
$result = call_user_func_array(
[$translation, $method],
$arguments
);
return $isSet ? $this : $result;
}
}