Files
2026-09-15 10:35:56 +08:00

78 lines
2.9 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Provider;
use Esun\MultiLocaleTranslation\Model\Google\AccessToken;
use Esun\MultiLocaleTranslation\Model\Google\Credentials;
use Esun\MultiLocaleTranslation\Model\Html\TranslatableTextExtractor;
use Esun\MultiLocaleTranslation\Model\Provider\Google;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Framework\HTTP\Client\CurlFactory;
use PHPUnit\Framework\TestCase;
class GoogleTest extends TestCase
{
public function testTranslatesOnlyVisibleHtmlTextAndRestoresMarkup(): void
{
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('isSetFlag')->willReturn(true);
$scopeConfig->method('getValue')->willReturnCallback(
static function (string $path): string {
return match (true) {
str_ends_with($path, '/location') => 'global',
str_ends_with($path, '/timeout') => '30',
default => '',
};
}
);
$credentials = $this->createMock(Credentials::class);
$credentials->method('get')->willReturn(['project_id' => 'test-project']);
$accessToken = $this->createMock(AccessToken::class);
$accessToken->method('get')->willReturn('test-token');
$curl = $this->createMock(Curl::class);
$curl->expects(self::once())->method('post')->with(
self::stringContains('test-project/locations/global:translateText'),
self::callback(static function (string $payload): bool {
$request = json_decode($payload, true);
return $request['contents'] === ['Hello', 'world']
&& $request['mimeType'] === 'text/html'
&& !str_contains($payload, '<style>')
&& !str_contains($payload, '<strong>');
})
);
$curl->method('getStatus')->willReturn(200);
$curl->method('getBody')->willReturn(json_encode([
'translations' => [
['translatedText' => 'Bonjour'],
['translatedText' => 'monde'],
],
], JSON_THROW_ON_ERROR));
$curlFactory = $this->createMock(CurlFactory::class);
$curlFactory->method('create')->willReturn($curl);
$provider = new Google(
$scopeConfig,
$credentials,
$accessToken,
$curlFactory,
new TranslatableTextExtractor()
);
$source = '<style>.hidden{display:none}</style><p>Hello <strong>world</strong></p>';
$result = $provider->translate([
'content' => ['value' => $source, 'is_html' => true],
], 'en', 'fr');
self::assertSame(
'<style>.hidden{display:none}</style><p>Bonjour <strong>monde</strong></p>',
$result['content']
);
}
}