-
Notifications
You must be signed in to change notification settings - Fork 27
custom formatter
jerrywham edited this page Nov 27, 2017
·
2 revisions
For custom formatter, the first thing to do is to create a new class that implements \Transphorm\Module and load your new formatter with configuration of \Transform
For example, create a file in "YOURPROJECT/Module" folder with the following code :
namespace YOURPROJECT\Module;
/** Module for loading a formatter with a locale */
class newFormat implements \Transphporm\Module {
public function load(\Transphporm\Config $config) {
$config->registerFormatter(new \YOURPROJECT\Formatter\StringFormatter());
}
}
Then the next thing to do is to create your formatter with your methods. For exemple, I want to format a string to use it in file name. File for StringFormatter has to be placed in "YOURPROJECT/Formatter/" folder (in this example) :
namespace YOURPROJECT\Formatter;
class StringFormatter
{
/**
* Protect a string against null byte
*
* @param string string to wash out
* @return string string washed
*/
private function nullbyteRemove($string) {
return str_replace("\0", '', $string);
}
/**
* Method for formatting a string by deleting invalid characters
*
* @param str string to format
* @param charset charset to use (default utf-8)
* @return string formatted string
*/
private function removeAccents($str,$charset='utf-8') {
$str = htmlentities($str, ENT_NOQUOTES, $charset);
$str = preg_replace('#\&([A-za-z])(?:acute|cedil|circ|grave|ring|tilde|uml|uro)\;#', '\1', $str);
$str = preg_replace('#\&([A-za-z]{2})(?:lig)\;#', '\1', $str); # pour les ligatures e.g. 'œ'
$str = preg_replace('#\&[^;]+\;#', '', $str); # supprime les autres caractères
return $str;
}
/**
* Method that converts a string of characters to a valid name format
*
* @param str string to format
* @return string valid url
**/
public function strToFileName($str,$lowerfy=false,$charset='utf-8') {
if ($lowerfy) $str = strtolower($this->removeAccents($str,$charset));
else $str = $this->removeAccents($str);
$str = str_replace(array('/','(',')',' '),'-',$str);
$str = preg_replace('/[^[:alnum:]]+/',' ',$str);
return $this->nullbyteRemove(strtr(trim($str), ' ', '-'));
}
}
Then, the last thing is to load module when you initiate Transphorm :
$template = new \Transphporm\Builder('layout.xml', 'render.tss',[
'\\Transphporm\\Module\\Basics',
'\\Transphporm\\Module\\Pseudo',
'\\Transphporm\\Module\\Format',
'\\YOURPROJECT\\Module\\Format',
'\\Transphporm\\Module\\Functions'
]);
$result = $template->output($data)->body;
As in previous examples :
$xml = '
<h1> </h1>
';
$tss = 'h1 {content: "My string to format"; format: strToFileName true}';
$template = new \Transphporm\Builder($xml, $tss);
$template->loadModule(new \YOURPROJECT\Module\Format);
echo $template->output()->body;
Prints :
<h1>my-string-to-format</h1>