Skip to content
This repository has been archived by the owner on Nov 2, 2020. It is now read-only.

Commit

Permalink
feat(i18n): Add i18n Support
Browse files Browse the repository at this point in the history
Add i18n Support, However the view is Working in progress.

BREAKING CHANGE: dbstructure of `Users` Change
  • Loading branch information
Rhilip committed Mar 13, 2019
1 parent 2119c2c commit 2a48b4c
Show file tree
Hide file tree
Showing 9 changed files with 249 additions and 6 deletions.
11 changes: 10 additions & 1 deletion apps/config/http_base.php
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,16 @@

'user' => [
'class' => Rid\User\User::class,
]
],

'i18n' => [
'class' => Rid\I18n\I18n::class,
'fileNamespace' => 'apps\lang',
'fallbackLang' => 'en',
'mergeFallback' => true,
'forcedLang' => null,
'allowedLangSet' => ['en', 'zh-CN']
],
],

// 类库配置
Expand Down
15 changes: 15 additions & 0 deletions apps/lang/en.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php
/**
* Created by PhpStorm.
* User: Rhilip
* Date: 2019/3/13
* Time: 20:45
*/

namespace apps\lang;


class en
{
const greeting = 'Hello World';
}
15 changes: 15 additions & 0 deletions apps/lang/zh_CN.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php
/**
* Created by PhpStorm.
* User: Rhilip
* Date: 2019/3/13
* Time: 21:06
*/

namespace apps\lang;


class zh_CN
{

}
8 changes: 5 additions & 3 deletions apps/views/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@
*/
?>

<?= $this->layout('layout/base') ?>
<?= $this->layout('layout/base') ?>

<?php $this->start('title')?>Index<?php $this->end();?>

<?php $this->start('container') ?>
<!-- Main component for a primary marketing message or call to action -->
<div class="jumbotron">
<h1>Navbar example</h1>
<p><strong>I'm sorry for broken page since I'm rebuilding.</strong></p>
<h1>Navbar <?= __('greeting',null,'zh-CN'); ?></h1>
<p><strong>I'm sorry for broken page since I'm rebuilding. <?= __('greet') ?></strong></p>
</div>
<?php $this->stop() ?>
3 changes: 2 additions & 1 deletion framework/Base/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
* @property \Rid\Config\DynamicConfig $config
* @property \Rid\Pool\ConnectionPool $connectionPool
* @property \Rid\User\User $user
* @property \Rid\I18n\I18n $i18n
*/
class Application extends BaseObject
{
Expand All @@ -36,7 +37,7 @@ class Application extends BaseObject
// 初始化事件
public function onInitialize()
{
parent::onInitialize(); // TODO: Change the autogenerated stub
parent::onInitialize();
// 快捷引用
\Rid::setApp($this);
// 错误注册
Expand Down
183 changes: 183 additions & 0 deletions framework/I18n/I18n.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
<?php
/**
* Created by PhpStorm.
* User: Rhilip
* Date: 2019/3/13
* Time: 19:55
*/

namespace Rid\I18n;

use Rid\Base\Component;

class I18n extends Component
{

/**
* Language file path
* This is the path for the language files.
*
* @var string
*/
public $fileNamespace = '\apps\lang';

/**
* Allowed language
* This is the set of language which is used to limit user languages. No-exist language will not accept.
*
* @var array
*/
public $allowedLangSet = ['en', 'zh-CN'];

/**
* Fallback language
* This is the language which is used when there is no language file for all other user languages. It has the lowest priority.
* Remember to create a language file for the fallback!!
*
* @var string
*/
public $fallbackLang = 'en';

/**
* Merge in fallback language
* Whether to merge current language's strings with the strings of the fallback language ($fallbackLang).
*
* @var bool
*/
public $mergeFallback = false;

/**
* Forced language
* If you want to force a specific language define it here.
*
* @var string
*/
public $forcedLang = null;

/*
* The following properties are only available after calling init().
*/
protected $lastLang = null;

public function onRequestBefore()
{
$lastLang = null;
}

/**
* getUserLangs()
* Returns the user languages
* Normally it returns an array like this:
* 1. Forced language
* 2. Language in $_GET['lang']
* 3. Language in $_SESSION['lang']
* 4. HTTP_ACCEPT_LANGUAGE
* 5. Fallback language
* Note: duplicate values are deleted.
*
* @param null $reqLang
* @return array with the user languages sorted by priority.
*/
public function getUserLangs($reqLang = null) {
$userLangs = array();

// Quick Return the last used language list
if ($this->lastLang != null && $reqLang == null) {
return $this->lastLang;
}

// Highest priority: forced language
if ($this->forcedLang != NULL) $userLangs[] = $this->forcedLang;

// 1st highest priority: required language
if ($reqLang != null) {
$userLangs[] = $reqLang;
} else {
// 2nd highest priority: GET parameter 'lang'
if (!is_null(app()->request->get('lang'))) $userLangs[] = app()->request->get('lang');

// 3rd highest priority: SESSION parameter 'lang'
if (!is_null(app()->user->getLang())) $userLangs[] = app()->user->getLang();

// 4th highest priority: HTTP_ACCEPT_LANGUAGE
if (!is_null(app()->request->header('accept_language'))) {
/**
* We get headers like this string 'en-US,en;q=0.8,uk;q=0.6,ru;q=0.4' (length=32)
* And then sort to an array like this
*
* array(size=4)
* 'en-US' => float 1
* 'en' => float 0.8
* 'uk' => float 0.6
* 'ru' => float 0.4
*
*/
$prefLocales = array_reduce(
explode(',', app()->request->header('accept_language')),
function ($res, $el) {
list($l, $q) = array_merge(explode(';q=', $el), [1]);
$res[$l] = (float)$q;
return $res;
}, []);
arsort($prefLocales);

foreach ($prefLocales as $part => $q) {
$userLangs[] = $part;
}
}
}

// Lowest priority: fallback
$userLangs[] = $this->fallbackLang;

$userLangs = array_unique($userLangs); // remove duplicate elements
$this->lastLang = $userLangs; // Store it for last use.
return $userLangs;
}

protected function getConfigClassName($langcode) {
$langcode = str_replace('-','_',$langcode);
return $this->fileNamespace . '\\' . $langcode;
}

private function getLangList($lang = null) {
$userLangs = $this->getUserLangs($lang);

// remove illegal userLangs
$userLangs2 = array();
foreach ($userLangs as $key => $value) {
// only allow a-z, A-Z and 0-9 and _ and -
if (preg_match('/^[a-zA-Z0-9_-]*$/', $value) === 1 && in_array($value, $this->allowedLangSet)) {
if (class_exists($this->getConfigClassName($value))) {
$userLangs2[] = $this->getConfigClassName($value); // change it to class name
} elseif (
// Fail back if main language exist
$value !== substr($value, 0, 2)
&& class_exists($this->getConfigClassName(substr($value, 0, 2)))) {
$userLangs2[] = $this->getConfigClassName(substr($value, 0, 2));
}
}
}

// remove duplicate elements
return array_unique($userLangs2);
}


public function trans($string, $args = null, $lang = null)
{
$langs = $this->getLangList($lang);

$return = '';
foreach ($langs as $item) {
try {
$return = constant($item . "::" . $string);
break;
} catch (\Exception $e) {
app()->log->warning('A no-exist translation hit.',['lang_class' => $item,'string' => $string]);
}
}

return $args ? vsprintf($return, $args) : $return;
}
}
10 changes: 10 additions & 0 deletions framework/User/UserTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ trait UserTrait

private $avatar;

private $lang;

private $create_at;
private $last_login_at;
private $last_access_at;
Expand Down Expand Up @@ -287,4 +289,12 @@ public function getActiveLeech()
}
return $active_leech;
}

/**
* @return mixed
*/
public function getLang()
{
return $this->lang;
}
}
7 changes: 7 additions & 0 deletions framework/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ function env($name = null, $default = '')
}
}

if (!function_exists('__')) {
function __($string, $avg = null, $lang = null)
{
return app()->i18n->trans($string, $avg, $lang);
}
}

if (!function_exists('tgo')) {

/** 创建一个带异常捕获的协程
Expand Down
3 changes: 2 additions & 1 deletion migration/ridpt.sql
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 08, 2019 at 08:30 AM
-- Generation Time: Mar 13, 2019 at 03:26 PM
-- Server version: 8.0.14
-- PHP Version: 7.3.1

Expand Down Expand Up @@ -598,6 +598,7 @@ CREATE TABLE IF NOT EXISTS `users` (
`bonus_seeding` decimal(20,2) UNSIGNED NOT NULL DEFAULT '0.00',
`bonus_invite` decimal(20,2) UNSIGNED NOT NULL DEFAULT '0.00',
`bonus_other` decimal(20,2) UNSIGNED NOT NULL DEFAULT '0.00',
`lang` varchar(10) NOT NULL DEFAULT 'en',
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `email` (`email`),
Expand Down

0 comments on commit 2a48b4c

Please sign in to comment.