Last active
October 15, 2019 15:48
-
-
Save Modelizer/12c8c3eb8f445ddc55202fcc4b4c09b1 to your computer and use it in GitHub Desktop.
Helper class to deal with placeholders and XML or HTML tags which should be replace in given text.
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 | |
/** | |
* Helper class to deal with placeholders and xml tags which should be replace in given text | |
* | |
* ---------- Example ---------- | |
* $sampleText = 'This is the <bold-underline>sample</bold-underline> code of {{user}}'. | |
* $placeholders = ['user' => 'Mohammed Mudassir']; | |
* $xml = ['bold-underline' => '<b style="text-decoration: underline'>%</b>'] | |
* | |
* $templateTranslation = new TemplateTranslation($placeholders, $xml); | |
* echo $template->process($sampleText); | |
* ---------- Example ---------- | |
* | |
* @author Mohammed Mudassir <[email protected]> | |
*/ | |
class TemplateTranslation | |
{ | |
/** @var array */ | |
protected $xml; | |
/** @var array */ | |
protected $placeholders; | |
/** | |
* @param array $placeholders | |
* @param array $xml | |
*/ | |
public function __construct(array $placeholders = [], array $xml = []) | |
{ | |
$this->placeholders = $placeholders; | |
$this->xml = $xml; | |
} | |
/** | |
* @param string $key | |
* @return string | |
*/ | |
public function process(string $key) | |
{ | |
return $this->processXml($this->processTags(__($key))); | |
} | |
/** | |
* XML are static values which get replace by system define HTML tag such as <style_link_1>text</style_link_1> | |
* Note: tags starts and ends like a HTML tag | |
* | |
* @param string $text | |
* @param array $xml | |
* @return string | |
*/ | |
public function processXml(string $text, $xml = []): string | |
{ | |
$expressions = []; | |
foreach (array_merge($this->xml, $xml) as $tag => $value) { | |
if (empty($tag)) { | |
continue; | |
} | |
$expressions["/<{$tag}>(.+)<\/{$tag}>/iU"] = str_replace('>%<', '>$1<', $value); | |
} | |
return preg_replace(array_keys($expressions), array_values($expressions), $text); | |
} | |
/** | |
* Tags are dynamic values which need to get replace by a placeholder such as {{click_link}} | |
* Note: tags starts with double parentheses | |
* | |
* @param string $text | |
* @param array $placeholders | |
* @return string | |
*/ | |
public function processTags(string $text, $placeholders = []): string | |
{ | |
$placeholders = array_merge($this->placeholders, $placeholders); | |
return preg_replace_callback('/(?>{{(?<placeholder>.*)}})+/iU', function (array $match) use ($placeholders) { | |
return array_get($placeholders, strtolower(trim((string)$match['placeholder']))); | |
}, $text); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment