Created
October 2, 2017 15:21
-
-
Save renepardon/9d3408b1ede334e1c5fde65031463194 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Carbon\Carbon; | |
use Illuminate\Support\Facades\Session as SessionFacade; | |
/** | |
* Trait I18nTrait | |
* | |
* @package App | |
*/ | |
trait I18nTrait | |
{ | |
/** | |
* @var array | |
*/ | |
protected $translations = []; | |
/** | |
* @var string | |
*/ | |
protected $locale; | |
/** | |
* @param string $locale | |
*/ | |
public function setUserLocale(string $locale = 'de') | |
{ | |
if (!in_array($locale, config('app.supported_locales'))) { | |
throw new \InvalidArgumentException(trans('Provided locale is not supported')); | |
} | |
$this->locale = $locale; | |
app()->setLocale($locale); | |
SessionFacade::put('_locale', $locale); | |
Carbon::setLocale($locale); | |
} | |
/** | |
* @param string $key | |
* | |
* @return string | |
*/ | |
public function translate(string $key): string | |
{ | |
if (!isset($this->translations[$this->locale])) { | |
$this->translations[$this->locale] = include(resource_path(sprintf('lang/%s/messages.php', $this->locale))); | |
} | |
if (isset($this->translations[$this->locale][$key])) { | |
return $this->translations[$this->locale][$key]; | |
} | |
// Default, return key again as no translation was found for current locale... | |
return $key; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment