add string builder
This commit is contained in:
parent
f62e975373
commit
dcb7bebd6b
46
core/String/StringBuilder.php
Normal file
46
core/String/StringBuilder.php
Normal file
|
@ -0,0 +1,46 @@
|
|||
<?php
|
||||
|
||||
namespace App\Core\String;
|
||||
|
||||
use Symfony\Component\PropertyAccess\PropertyAccess;
|
||||
use Symfony\Component\PropertyAccess\PropertyAccessor;
|
||||
use function Symfony\Component\String\u;
|
||||
|
||||
/**
|
||||
* class StringBuilder.
|
||||
*
|
||||
* @author Simon Vieille <simon@deblan.fr>
|
||||
*/
|
||||
class StringBuilder
|
||||
{
|
||||
protected PropertyAccessor $propertyAccessor;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->propertyAccessor = PropertyAccess::createPropertyAccessorBuilder()
|
||||
->getPropertyAccessor()
|
||||
;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a string and inject values from given object.
|
||||
*
|
||||
* @param mixed $object
|
||||
*/
|
||||
public function build(string $format, $object): string
|
||||
{
|
||||
if (!is_array($object) && !is_object($object)) {
|
||||
return $format;
|
||||
}
|
||||
|
||||
preg_match_all('/\{([a-zA-Z0-9\.]+)\}/i', $format, $matches, PREG_SET_ORDER);
|
||||
|
||||
foreach ($matches as $match) {
|
||||
$propertyValue = $this->propertyAccessor->getValue($object, $match[1]);
|
||||
|
||||
$format = u($format)->replace($match[0], $propertyValue);
|
||||
}
|
||||
|
||||
return $format;
|
||||
}
|
||||
}
|
32
core/Twig/Extension/StringExtension.php
Normal file
32
core/Twig/Extension/StringExtension.php
Normal file
|
@ -0,0 +1,32 @@
|
|||
<?php
|
||||
|
||||
namespace App\Core\Twig\Extension;
|
||||
|
||||
use Twig\Extension\AbstractExtension;
|
||||
use Twig\TwigFilter;
|
||||
use App\Core\String\StringBuilder;
|
||||
|
||||
class StringExtension extends AbstractExtension
|
||||
{
|
||||
protected StringBuilder $stringBuilder;
|
||||
|
||||
public function __construct(StringBuilder $stringBuilder)
|
||||
{
|
||||
$this->stringBuilder = $stringBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFilters()
|
||||
{
|
||||
return [
|
||||
new TwigFilter('build_string', [$this, 'buildString']),
|
||||
];
|
||||
}
|
||||
|
||||
public function buildString(string $format, $object): string
|
||||
{
|
||||
return $this->stringBuilder->build($format, $object);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue