Skip to content

Instantly share code, notes, and snippets.

@imorte
Created August 4, 2017 07:55
Show Gist options
  • Select an option

  • Save imorte/75f8037c090f1a31f82967f19ba6e2ad to your computer and use it in GitHub Desktop.

Select an option

Save imorte/75f8037c090f1a31f82967f19ba6e2ad to your computer and use it in GitHub Desktop.
<?php
namespace App;
/**
* Class Translation
* @package App\Translate
*/
class Translation {
// Slashes is required
/**
* @var string
*/
public $langFolder = '/local/lang/';
/**
* @var string
*/
private static $currentLanguage = '';
public $dirs = [];
protected static $instance;
public static function getInstance()
{
if (static::$instance === null) {
static::$instance = new static();
}
return static::$instance;
}
public function __construct()
{
$this->choiceLang();
}
public static function getRu()
{
return 'ru';
}
public static function getEng()
{
return 'en';
}
public static function getLang()
{
return static::$currentLanguage;
}
public function setLang($lang)
{
static::$currentLanguage = $lang;
return $this;
}
public function isDefaultLanguage()
{
return $this->getLang() === 'ru';
}
public function generateUri()
{
$currentHost = $_SERVER['HTTP_HOST'];
$this->currentLanguage = $this->getLang();
$explodedCurrentHost = explode('.', $currentHost);
$returnedHost = '';
if(static::$currentLanguage !== $this->getRu()) {
$returnedHost['ru'] = join('.', array_slice($explodedCurrentHost, 1));
} else {
$returnedHost['ru'] = $currentHost;
}
if(static::$currentLanguage === $this->getEng()) {
$returnedHost['en'] = $currentHost;
} else {
$returnedHost['en'] = $this->getEng() . '.' . $currentHost;
}
return $returnedHost;
}
public function choiceLang()
{
$this->setDirToLoad($this->langFolder);
$httpHost = $_SERVER['HTTP_HOST'];
$httpHostLang = explode('.', $httpHost)[0];
switch ($httpHostLang) {
case 'en':
$currentLang = 'en'; break;
default:
$currentLang = 'ru';
}
$this->setLang($currentLang);
return $this;
}
public function translateNow($ru, $en)
{
switch ($this->getLang()) {
case 'ru':
return $ru; break;
case 'en':
return $en; break;
default:
return null;
}
}
/**
* Get all files in dir
* @param string $dir
* @return Translation
*/
public function setDirToLoad(string $dir): Translation
{
$this->dirs = $files = glob($dir . $this->getLang() . '/*');
return $this;
}
public function autoload()
{
foreach ($this->dirs as $dir) {
require_once $dir;
}
}
public function getIncludes()
{
return $this->dirs;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment