Repository navigation
Expand file tree
/
Copy pathPreferencesFormType.php
More file actions
84 lines (70 loc) · 2.31 KB
/
Copy pathPreferencesFormType.php
File metadata and controls
84 lines (70 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
namespace SyncEngine\Form;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Intl\Locales;
use Symfony\Component\OptionsResolver\OptionsResolver;
use SyncEngine\Service\Preferences;
class PreferencesFormType extends AbstractType
{
private array $availableLocales;
public function __construct(
private readonly Preferences $preferences,
#[Autowire( '%syncengine.dir.translations%' )]
private string $transDir = __DIR__ . '/../../translations',
) {}
public function getAvailableLanguages()
{
if ( isset ( $this->availableLocales ) ) {
return $this->availableLocales;
}
$finder = new Finder();
$coreTranslations = $finder->in($this->transDir)->files()->name( 'messages*');
$availableLocales = [];
foreach ( $coreTranslations as $file ) {
if ( preg_match( '/^messages(?:\+intl-icu)?\.([^.]+)\./', $file->getFilename(), $matches ) ) {
$availableLocales[ $matches[1] ] = true;
}
}
$this->availableLocales = $availableLocales;
return $availableLocales;
}
public function buildForm( FormBuilderInterface $builder, array $options ): void
{
$localeChoices = [];
$availableLocales = $this->getAvailableLanguages();
foreach ( Locales::getNames() as $locale => $name ) {
// Fix this if statement to check if the locale is in the core translations.
// File format is messages.{locale}.{ext} or messages+intl-icu.{locale}.{ext}.
if ( isset( $availableLocales[ $locale ] ) ) {
$localName = Locales::getName( $locale, $locale );
$label = $locale . ': ' . $localName . ' | ' . $name;
$localeChoices[ $label ] = $locale;
}
}
asort( $localeChoices );
$builder
->add('locale', ChoiceType::class, [
'row_attr' => [
'class' => 'form-floating mb-3',
],
'choices' => $localeChoices,
]);
}
public function configureOptions( OptionsResolver $resolver ): void
{
$availableLocales = $this->getAvailableLanguages();
$userLocale = $this->preferences->get('locale');
if ( ! isset( $availableLocales[ $userLocale ] ) ) {
$userLocale = 'en';
}
$resolver->setDefaults( [
'data' => [
'locale' => $userLocale,
],
] );
}
}