Skip to content

Commit

Permalink
TagProcessor: added support for empty elements (<br> by default)
Browse files Browse the repository at this point in the history
  • Loading branch information
janpecha committed Feb 2, 2024
1 parent 0298cd9 commit c05d437
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
9 changes: 9 additions & 0 deletions src/Ast/Element.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,15 @@ public function __construct($name, array $attributes = [])
}


/**
* @return non-empty-string
*/
public function getName()
{
return $this->name;
}


public function format(array $parameters, Locale $locale)
{
$attrs = [];
Expand Down
22 changes: 20 additions & 2 deletions src/Processors/TagProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,24 @@ class TagProcessor implements \Inteve\Translator\MessageProcessor
/** @var \Inteve\Translator\MessageProcessor */
private $textPartsProcessor;

/** @var array<non-empty-string, TRUE> */
private $emptyElements;

public function __construct(\Inteve\Translator\MessageProcessor $textPartsProcessor = NULL)

/**
* @param array<non-empty-string> $emptyElements
*/
public function __construct(
\Inteve\Translator\MessageProcessor $textPartsProcessor = NULL,
array $emptyElements = ['br']
)
{
$this->textPartsProcessor = $textPartsProcessor !== NULL ? $textPartsProcessor : new ParametersProcessor;
$this->emptyElements = [];

foreach ($emptyElements as $emptyElement) {
$this->emptyElements[strtolower($emptyElement)] = TRUE;
}
}


Expand All @@ -37,7 +51,7 @@ private function parseContent(Utils\StringParser $parser)
if (($part = $this->tryParseElement($parser)) !== NULL) {
$parts[] = $part;

} else { // invalid parameter
} else { // invalid tag
$parts[] = $parser->consume(1);
}

Expand Down Expand Up @@ -94,6 +108,10 @@ private function tryParseElement(Utils\StringParser $parser)

$parser->consumeText('>');

if (isset($this->emptyElements[$element->getName()])) {
return $element;
}

while (!$parser->isCurrent('</')) {
if ($parser->isCurrent('<')) {
$subElement = $this->tryParseElement($parser);
Expand Down
10 changes: 10 additions & 0 deletions tests/Translator/TagProcessor.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,13 @@ test('Complex', function () {
),
]), $processor->processMessage('{$param} lorem, <b title="Ipsum {$title}">{$name} <i>{$count}</i></b>'));
});


test('Empty elements', function () {
$processor = new TagProcessor;
Assert::equal(new Ast\MessageText([
'Lorem ipsum',
Ast\Element::create('br'),
'dolor sit amet',
]), $processor->processMessage('Lorem ipsum<br>dolor sit amet'));
});

0 comments on commit c05d437

Please sign in to comment.