Skip to content

Commit

Permalink
Возможность в значениях текстовок использовать другие ключи по аналог…
Browse files Browse the repository at this point in the history
…ии с конфигом, например, 'title' => 'My title ___main___'
  • Loading branch information
mzhelskiy committed Jul 30, 2014
1 parent f85a154 commit 69cb2e0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
2 changes: 1 addition & 1 deletion classes/engine/Engine.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ static public function getInstance() {

/**
* Инициализация ядра движка
*
* todo: запретить выполнять повторную инициализацию
*/
public function Init() {
/**
Expand Down
30 changes: 30 additions & 0 deletions classes/modules/lang/Lang.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,10 @@ public function Get($sName,$aReplace=array(),$bDelete=true) {
return $sName;
}
}
/**
* Заменяем вхождение других ключей вида ___lang_key___
*/
$sLang=$this->ReplaceKey($sLang);

if(is_array($aReplace)&&count($aReplace)&&is_string($sLang)) {
foreach ($aReplace as $sFrom => $sTo) {
Expand All @@ -270,6 +274,32 @@ public function Get($sName,$aReplace=array(),$bDelete=true) {
}
return $sLang;
}
/**
* Заменяет плейсхолдеры ключей в значениях текстовки
*
* @param string|array $msg Значение текстовки
* @return array|mixed
*/
protected function ReplaceKey($msg) {
if(is_array($msg)) {
foreach($msg as $k=>$v) {
$k_replaced = $this->ReplaceKey($k);
if($k==$k_replaced) {
$msg[$k] = $this->ReplaceKey($v);
} else {
$msg[$k_replaced] = $this->ReplaceKey($v);
unset($msg[$k]);
}
}
} else {
if(preg_match_all('~___([\S|\.]+)___~Ui',$msg,$aMatch,PREG_SET_ORDER)) {
foreach($aMatch as $aItem) {
$msg=str_replace('___'.$aItem[1].'___',$this->Get($aItem[1]),$msg);
}
}
}
return $msg;
}
/**
* Добавить к текстовкам массив сообщений
*
Expand Down

7 comments on commit 69cb2e0

@psnet
Copy link

@psnet psnet commented on 69cb2e0 Jul 30, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

как идея интересно, но до сих пор смущает: будет ли польза, а вот то что для каждой текстовки ещё будет регулярка запускаться (коих немало) - нагруженность.

Может перед тем как отправить в метод:
69cb2e0#diff-0275aa66ae03035f6029dd2c29c54a50R263

сделать проверку:

if (strpos('___', $sLang) !== false) {
    $sLang=$this->ReplaceKey($sLang);
}

чтобы запускать регулярку только в случае если есть что менять.

@mzhelskiy
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

можно запустить тест: посмотреть сколько раз вызывается get для главной страницы, умножить на 2 и замерить затраты на preg_match

@psnet
Copy link

@psnet psnet commented on 69cb2e0 Jul 31, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

но очевидно же что в значениях это будет использоваться крайне редко поэтому ощущается необходимость в strpos, которая в любом случае менее затратна

@mzhelskiy
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не очевиден реальный размер экономии

@psnet
Copy link

@psnet psnet commented on 69cb2e0 Jul 31, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

очень редко будет использоваться (как минимум пока) ссылка на другие текстовки в значении, а регулярка будет запускаться всегда для каждого значения.

регулярки более ресурсоёмкие чем быстрый strpos.
если поставить условие то для каждой текстовки будет легкая проверка чем запуск машины регулярных выражений.

@mzhelskiy
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это понятно
вопрос в том на спичках эта экономия или нет

@psnet
Copy link

@psnet psnet commented on 69cb2e0 Jul 31, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

разница в скорости выполнения однозначно будет в два раза. порядки времени неизвестны

Please sign in to comment.