Files
esun3d/app/code/Esun/MultiLocaleTranslation/Model/Google/Credentials.php
T
2026-09-15 10:35:56 +08:00

67 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Google;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
class Credentials
{
private const XML_PATH_FILE = 'esun_multilocale_translation/google/credentials_file';
private ?array $credentials = null;
public function __construct(
private readonly ScopeConfigInterface $scopeConfig,
private readonly Filesystem $filesystem
) {
}
/**
* @return array<string, string>
*/
public function get(): array
{
if ($this->credentials !== null) {
return $this->credentials;
}
$filename = basename((string)$this->scopeConfig->getValue(self::XML_PATH_FILE));
if ($filename === '') {
throw new LocalizedException(__('Google service account JSON is not configured.'));
}
$directory = $this->filesystem->getDirectoryRead(DirectoryList::VAR_DIR);
$relativePath = 'esun/multilocale_translation/google/' . $filename;
if (!$directory->isFile($relativePath)) {
throw new LocalizedException(__('The configured Google service account JSON file was not found.'));
}
try {
$data = json_decode($directory->readFile($relativePath), true, 32, JSON_THROW_ON_ERROR);
} catch (\Throwable) {
throw new LocalizedException(__('The configured Google service account JSON is invalid.'));
}
if (!is_array($data)
|| ($data['type'] ?? '') !== 'service_account'
|| empty($data['project_id'])
|| empty($data['client_email'])
|| empty($data['private_key'])
) {
throw new LocalizedException(__('The configured JSON is not a valid Google service account key.'));
}
$this->credentials = array_map(
static fn (mixed $value): string => is_scalar($value) ? (string)$value : '',
$data
);
return $this->credentials;
}
}