add string builder

This commit is contained in:
Simon Vieille 2021-03-22 21:35:03 +01:00
parent f62e975373
commit dcb7bebd6b
2 changed files with 78 additions and 0 deletions

View 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;
}
}

View 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);
}
}