Last active
September 11, 2015 15:40
-
-
Save sergiors/9b1c0d205ed450a2d006 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
namespace Inbep\Twig\Extension; | |
/** | |
* @author Sérgio Rafael Siqueira <[email protected]> | |
*/ | |
class MaskExtension extends \Twig_Extension | |
{ | |
private $masks = [ | |
'phone' => [ | |
'pattern' => '/^(\d{2})(\d{4,5})(\d{4})$/', | |
'replace' => '($1) $2-$3' | |
], | |
'cpf' => [ | |
'pattern' => '/^(\d{3})(\d{3})(\d{3})(\d{2})$/', | |
'replace' => '$1.$2.$3-$4' | |
], | |
'cnpj' => [ | |
'pattern' => '/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/', | |
'replace' => '$1.$2.$3/$4-$5' | |
], | |
'cep' => [ | |
'pattern' => '/^(\d{5})(\d{3})$/', | |
'replace' => '$1-$2' | |
] | |
]; | |
/** | |
* @return array | |
*/ | |
public function getFilters() | |
{ | |
return [ | |
new \Twig_SimpleFilter('masked', [$this, 'replace']), | |
]; | |
} | |
/** | |
* @param mixed $value | |
* @param string $mask | |
* @return string | |
*/ | |
public function replace($value, $mask) | |
{ | |
if (!isset($this->masks[$mask])) { | |
throw new \InvalidArgumentException( | |
sprintf( | |
'The second parameter may be the following: %s.', | |
join(', ', array_keys($this->masks)) | |
) | |
); | |
} | |
$pattern = $this->masks[$mask]['pattern']; | |
$replace = $this->masks[$mask]['replace']; | |
return preg_replace($pattern, $replace, $value); | |
} | |
/** | |
* @return string | |
*/ | |
public function getName() | |
{ | |
return 'mask'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment