chill-bundles/src/Bundle/ChillMainBundle/Templating/TranslatableStringHelper.php

57 lines
1.6 KiB
PHP

<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Templating;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Contracts\Translation\TranslatorInterface;
final readonly class TranslatableStringHelper implements TranslatableStringHelperInterface
{
private string $defaultLocale;
public function __construct(private RequestStack $requestStack, private TranslatorInterface $translator, ParameterBagInterface $parameterBag)
{
$this->defaultLocale = $parameterBag->get('kernel.default_locale');
}
public function localize(array $translatableStrings): ?string
{
if ([] === $translatableStrings) {
return null;
}
$request = $this->requestStack->getCurrentRequest();
$language = null === $request ? $this->defaultLocale : $request->getLocale();
if (\array_key_exists($language, $translatableStrings)) {
return $translatableStrings[$language];
}
foreach ($this->translator->getFallbackLocales() as $locale) {
if (\array_key_exists($locale, $translatableStrings)) {
return $translatableStrings[$locale];
}
}
// no fallback translation... trying the first available
$langs = array_keys($translatableStrings);
if ([] === $langs) {
return '';
}
return $translatableStrings[$langs[0]];
}
}