Skip to content

Commit eb17b77

Browse files
committed
fix(translator): reject missing locales early
1 parent e599cfd commit eb17b77

3 files changed

Lines changed: 28 additions & 1 deletion

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php
2+
3+
namespace ProgrammatorDev\FluentValidator\Exception;
4+
5+
class NoSuchTranslationException extends \RuntimeException
6+
{
7+
public function __construct(string $locale)
8+
{
9+
$message = sprintf('Translation for locale "%s" was not found.', $locale);
10+
11+
parent::__construct($message);
12+
}
13+
}

src/Translator/Translator.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace ProgrammatorDev\FluentValidator\Translator;
44

55
use Composer\InstalledVersions;
6+
use ProgrammatorDev\FluentValidator\Exception\NoSuchTranslationException;
67
use Symfony\Component\Translation\Loader\XliffFileLoader;
78
use Symfony\Contracts\Translation\TranslatorInterface;
89

@@ -16,6 +17,10 @@ public function __construct(private string $locale)
1617
$packagePath = InstalledVersions::getInstallPath('symfony/validator');
1718
$resourcePath = sprintf('%s/Resources/translations/validators.%s.xlf', $packagePath, $this->locale);
1819

20+
if (!is_file($resourcePath)) {
21+
throw new NoSuchTranslationException($this->locale);
22+
}
23+
1924
$this->translator = new \Symfony\Component\Translation\Translator($this->locale);
2025
$this->translator->addLoader('xlf', new XliffFileLoader());
2126
$this->translator->addResource('xlf', $resourcePath, $this->locale);
@@ -30,4 +35,4 @@ public function getLocale(): string
3035
{
3136
return $this->locale;
3237
}
33-
}
38+
}

tests/ValidatorTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace ProgrammatorDev\FluentValidator\Test;
44

55
use ProgrammatorDev\FluentValidator\Exception\NoSuchConstraintException;
6+
use ProgrammatorDev\FluentValidator\Exception\NoSuchTranslationException;
67
use ProgrammatorDev\FluentValidator\Exception\ValidationFailedException;
78
use ProgrammatorDev\FluentValidator\Translator\Translator;
89
use ProgrammatorDev\FluentValidator\Validator;
@@ -135,6 +136,14 @@ public function testSetTranslator(): void
135136
$this->assertEquals('Este valor não deveria ser vazio.', $violations->get(0)->getMessage());
136137
}
137138

139+
public function testSetTranslatorThatDoesNotExist(): void
140+
{
141+
$this->expectException(NoSuchTranslationException::class);
142+
$this->expectExceptionMessage('Translation for locale "zz" was not found.');
143+
144+
new Translator('zz');
145+
}
146+
138147
public function testResetClearsTranslator(): void
139148
{
140149
Validator::setTranslator(new Translator('pt'));

0 commit comments

Comments
 (0)