Skip to content

Commit

Permalink
php-gettext#282 Added checks for invalid newlines and duplicated entries
Browse files Browse the repository at this point in the history
  • Loading branch information
jonasraoni committed Jul 23, 2022
1 parent 5c4dfd3 commit 2c244a9
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/Loader/StrictPoLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ private function newEntry(): void
*/
private function saveEntry(): void
{
if ($this->translations->getTranslations()[$this->translation->getId()] ?? null) {
throw new Exception("Duplicated entry at byte {$this->position}");
}
$this->translations->add($this->translation);
}

Expand Down Expand Up @@ -328,6 +331,7 @@ private function readContext(): bool
private function readOriginal(): void
{
$data = $this->readIdentifier('msgid', true);
$this->checkNewLine($data, 'msgid');
$this->translation = $this->translation->withOriginal($data);
}

Expand All @@ -339,6 +343,7 @@ private function readPlural(): bool
if (($data = $this->readIdentifier('msgid_plural')) === null) {
return false;
}
$this->checkNewLine($data, 'msgid_plural');
$this->translation->setPlural($data);

return true;
Expand All @@ -355,6 +360,10 @@ private function readTranslation(): void
}
$this->readWhiteSpace();
$data = $this->readQuotedString();
// The header might be surrounded by newlines
if ($this->translation->getOriginal() !== '') {
$this->checkNewLine($data, 'msgstr');
}
$this->translation->translate($data);
}

Expand Down Expand Up @@ -392,6 +401,7 @@ private function readPluralTranslation(bool $throwIfNotFound = false): bool
$this->readWhiteSpace();
$data = $this->readQuotedString();
$translations[] = $data;
$this->checkNewLine($data, 'msgstr');
$this->translation->translate(array_shift($translations));
$this->translation->translatePlural(...$translations);

Expand Down Expand Up @@ -452,4 +462,15 @@ private function readHeaders(?string $string): array

return $headers;
}

/**
* Ensures the data doesn't start nor end with a newline
*/
private function checkNewLine(string $data, string $context): void
{
if (($first = substr($data, 0, 1)) === "\n" || $first === "\r"
|| ($last = substr($data, -1)) === "\n" || $last === "\n") {
throw new Exception("$context cannot start nor end with a newline at byte {$this->position}");
}
}
}

0 comments on commit 2c244a9

Please sign in to comment.