Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 53 additions & 6 deletions src/Parser/XliffParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
use InvalidArgumentException;
use SimpleXMLElement;

use function preg_match;
use function strtolower;

/**
* XliffParser.
*
Expand Down Expand Up @@ -112,14 +115,58 @@ public static function getSupportedFileExtensions(): array

public function getLanguage(): string
{
if (preg_match(
'/^([a-z]{2})\./i',
$this->getFileName(),
$matches,
)) {
return $matches[1];
return $this->getLanguageFromFileName() ?? $this->getSourceLanguage();
}

public function isVersion2(): bool
{
return $this->isVersion2;
}

/**
* Extracts the expected locale from the filename, supporting both
* prefix convention (de.locallang.xlf, TYPO3 style) and
* suffix convention (messages.de.xlf, Symfony/Laravel style).
* Returns null if the filename carries no locale.
*/
public function getLanguageFromFileName(): ?string
{
$fileName = $this->getFileName();

// Prefix convention: de.locallang.xlf, de_AT.locallang.xlf, de_DE.locallang.xlf
if (preg_match('/^([a-z]{2})(?:[-_][A-Z]{2})?\./i', $fileName, $matches)) {
return strtolower($matches[1]);
}

// Suffix convention: messages.de.xlf, messages.de_AT.xlf, messages.de_DE.xlf
if (preg_match('/\.([a-z]{2})(?:[-_][A-Z]{2})?\.(?:xlf|xliff)$/i', $fileName, $matches)) {
return strtolower($matches[1]);
}

return null;
}
Comment thread
maikschneider marked this conversation as resolved.

/**
* Returns the normalized target language declared in the XLIFF file, or null if not set.
* Region suffix is stripped to match getLanguageFromFileName() behavior (e.g. "de-AT" → "de").
* XLIFF 1.x: target-language attribute on <file>.
* XLIFF 2.x: trgLang attribute on <xliff>.
*/
public function getTargetLanguage(): ?string
{
$lang = $this->isVersion2
? (string) ($this->xml['trgLang'] ?? '')
: (string) ($this->xml->file['target-language'] ?? '');

if ('' === $lang) {
return null;
}

return strtolower((string) preg_replace('/[-_][^-_]+$/', '', $lang));
}

private function getSourceLanguage(): string
{
if ($this->isVersion2) {
return (string) ($this->xml['srcLang'] ?? '');
}
Expand Down
78 changes: 59 additions & 19 deletions src/Validator/XliffSchemaValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Symfony\Component\Translation\Util\XliffUtils;

use function sprintf;
use function strtolower;

/**
* XliffSchemaValidator.
Expand All @@ -31,40 +32,79 @@ class XliffSchemaValidator extends AbstractValidator implements ValidatorInterfa
{
public function processFile(ParserInterface $file): array
{
try {
/*
* With XmlUtils::loadFile() we always get a strange symfony error related to global composer autoloading issue.
* Call to undefined method Symfony\Component\Filesystem\Filesystem::readFile()
*/
if (!file_exists($file->getFilePath())) {
$this->logger?->error('File does not exist: '.$file->getFileName());

return [];
}
/*
* With XmlUtils::loadFile() we always get a strange symfony error related to global composer autoloading issue.
* Call to undefined method Symfony\Component\Filesystem\Filesystem::readFile()
*/
if (!file_exists($file->getFilePath())) {
$this->logger?->error('File does not exist: '.$file->getFileName());

return [];
}

$fileContent = file_get_contents($file->getFilePath());
if (false === $fileContent) {
$this->logger?->error('Failed to read file: '.$file->getFileName());
$fileContent = file_get_contents($file->getFilePath());
if (false === $fileContent) {
$this->logger?->error('Failed to read file: '.$file->getFileName());

return [];
}
return [];
}

try {
$dom = XmlUtils::parse($fileContent);
} catch (Exception $e) {
$this->logger?->error('Failed to parse XML: '.$e->getMessage());

return [];
}

// Schema validation — may throw for unsupported XLIFF versions (e.g. 2.x)
$errors = [];
try {
$errors = XliffUtils::validateSchema($dom);
} catch (Exception $e) {
if (str_contains($e->getMessage(), 'No support implemented for loading XLIFF version')) {
$this->logger?->notice(sprintf('Skipping %s: %s', $this->getShortName(), $e->getMessage()));
} else {
Comment on lines 65 to 67

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Notice wording is misleading (Skipping vs actual behavior).

Line 68 logs “Skipping …”, but the method continues and may still return custom target-language issues. Please make the notice explicit that only schema validation is skipped.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/Validator/XliffSchemaValidator.php` around lines 67 - 69, Change the
misleading log message so it explicitly states that only schema validation is
being skipped (not the whole validation), e.g. update the notice in
XliffSchemaValidator (where the exception is caught and you call
$this->logger?->notice(sprintf('Skipping %s: %s', $this->getShortName(),
$e->getMessage()))) to something like "Skipping schema validation for %s: %s" or
"Schema validation skipped for %s: %s" so it clearly references schema
validation and still includes $this->getShortName() and $e->getMessage().

$this->logger?->error('Failed to validate XML schema: '.$e->getMessage());
}

return [];
}

if (!empty($errors)) {
// Additional check: if filename encodes a locale, verify it matches target-language in the file header
if (!$file instanceof XliffParser) {
return $errors;
}

return [];
$expectedLanguage = $file->getLanguageFromFileName();
if (null !== $expectedLanguage) {
$targetLang = $file->getTargetLanguage();
$isVersion2 = $file->isVersion2();
$attribute = $isVersion2 ? 'trgLang' : 'target-language';
$element = $isVersion2 ? '<xliff>' : '<file>';

if (null === $targetLang) {
$errors[] = [
'message' => sprintf(
'Missing "%s" attribute on %s node; expected "%s" based on filename',
$attribute,
$element,
$expectedLanguage,
),
'level' => 'ERROR',
];
} elseif (strtolower($targetLang) !== $expectedLanguage) {
$errors[] = [
'message' => sprintf(
'"%s" attribute "%s" does not match filename language "%s"',
$attribute,
$targetLang,
$expectedLanguage,
),
'level' => 'ERROR',
];
}
}

return $errors;
}

public function formatIssueMessage(Issue $issue, string $prefix = ''): string
Expand Down
108 changes: 108 additions & 0 deletions tests/src/Parser/XliffParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,114 @@ public function testGetLanguageFromSrcLangAttributeXliff2(): void
$this->assertSame('en', $parser->getLanguage());
}

public function testGetLanguageFromFileNamePrefixConvention(): void
{
$parser = new XliffParser($this->prefixedXliffFile); // de.messages.xlf
$this->assertSame('de', $parser->getLanguageFromFileName());
}

public function testGetLanguageFromFileNameSuffixConvention(): void
{
$parser = new XliffParser($this->targetLanguageXliffFile); // messages.de.xlf
$this->assertSame('de', $parser->getLanguageFromFileName());
}

public function testGetLanguageFromFileNamePrefixConventionWithRegion(): void
{
$file = $this->tempDir.'/de_DE.locallang.xlf';
file_put_contents($file, $this->prefixedXliffContent);

$parser = new XliffParser($file);
$this->assertSame('de', $parser->getLanguageFromFileName());
}

public function testGetLanguageFromFileNameSuffixConventionWithRegion(): void
{
$file = $this->tempDir.'/messages.de_DE.xlf';
file_put_contents($file, $this->targetLanguageXliffContent);

$parser = new XliffParser($file);
$this->assertSame('de', $parser->getLanguageFromFileName());
}

public function testGetLanguageFromFileNameReturnsNullForSourceFile(): void
{
$parser = new XliffParser($this->validXliffFile); // messages.xlf — no locale
$this->assertNull($parser->getLanguageFromFileName());
}

public function testGetLanguageFromFileNameReturnsNullForXliff2SourceFile(): void
{
$parser = new XliffParser($this->xliff2File); // messages_v2.xlf — no locale
$this->assertNull($parser->getLanguageFromFileName());
}

public function testGetTargetLanguageReturnsValueWhenSet(): void
{
$parser = new XliffParser($this->targetLanguageXliffFile); // target-language="de"
$this->assertSame('de', $parser->getTargetLanguage());
}

public function testGetTargetLanguageReturnsNullWhenNotSet(): void
{
$parser = new XliffParser($this->validXliffFile); // no target-language attribute
$this->assertNull($parser->getTargetLanguage());
}

public function testGetTargetLanguageXliff2ReturnsValueWhenSet(): void
{
$parser = new XliffParser($this->xliff2TargetFile); // trgLang="de"
$this->assertSame('de', $parser->getTargetLanguage());
}

public function testGetTargetLanguageXliff2ReturnsNullWhenNotSet(): void
{
$parser = new XliffParser($this->xliff2File); // no trgLang
$this->assertNull($parser->getTargetLanguage());
}

public function testGetTargetLanguageStripsRegionSuffixWithHyphen(): void
{
$file = $this->tempDir.'/region_hyphen.xlf';
file_put_contents($file, <<<'EOT'
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
<file source-language="en" target-language="de-AT" datatype="plaintext" original="region_hyphen.xlf">
<body><trans-unit id="k"><source>x</source></trans-unit></body>
</file>
</xliff>
EOT);
$this->assertSame('de', (new XliffParser($file))->getTargetLanguage());
}

public function testGetTargetLanguageStripsRegionSuffixWithUnderscore(): void
{
$file = $this->tempDir.'/region_underscore.xlf';
file_put_contents($file, <<<'EOT'
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
<file source-language="en" target-language="de_AT" datatype="plaintext" original="region_underscore.xlf">
<body><trans-unit id="k"><source>x</source></trans-unit></body>
</file>
</xliff>
EOT);
$this->assertSame('de', (new XliffParser($file))->getTargetLanguage());
}

public function testGetTargetLanguageXliff2StripsRegionSuffix(): void
{
$file = $this->tempDir.'/region_v2.xlf';
file_put_contents($file, <<<'EOT'
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0" srcLang="en" trgLang="de-AT">
<file id="messages">
<unit id="k"><segment><source>x</source></segment></unit>
</file>
</xliff>
EOT);
$this->assertSame('de', (new XliffParser($file))->getTargetLanguage());
}

public function testGetContentByKeyFallsBackToSourceWhenTargetIsEmptyXliff2(): void
{
$fallbackFile = $this->tempDir.'/v2_fallback.xlf';
Expand Down
Loading