Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix JsonException: Malformed UTF-8 characters, possibly incorrectly encoded #43

Merged
merged 4 commits into from
Apr 24, 2024
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
6 changes: 6 additions & 0 deletions src/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,12 @@ public function translateText($texts, ?string $sourceLang, string $targetLang, a
$this->checkStatusCode($response);

list(, $content) = $response;

// Deepl API responses might have invalid UTF8 sequence
// @see https://github.com/DeepLcom/deepl-php/pull/43
mb_substitute_character(0xFFFD);
$content = mb_convert_encoding($content, 'UTF-8', 'UTF-8');

try {
$decoded = json_decode($content, true, 512, \JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
Expand Down
15 changes: 15 additions & 0 deletions tests/TranslateTextTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,21 @@ public function testMultipleText(?ClientInterface $httpClient)
$this->assertEquals('en', $result[1]->detectedSourceLang);
}

/**
* @dataProvider provideHttpClient
*/
public function testHandlingResponseWithInvalidUtf8(?ClientInterface $httpClient)
{
$this->needsRealServer();
$translator = $this->makeTranslator([TranslatorOptions::HTTP_CLIENT => $httpClient]);
$input = 'Portal<span></span>';
$result = $translator->translateText($input, 'en', 'fr', [
TranslateTextOptions::TAG_HANDLING => 'xml',
TranslateTextOptions::IGNORE_TAGS => 'notranslate',
]);
$this->assertInstanceOf(TextResult::class, $result);
}

/**
* @dataProvider provideHttpClient
*/
Expand Down