|
28 | 28 | use Symfony\Component\Form\FormInterface; |
29 | 29 | use Symfony\Component\Form\FormView; |
30 | 30 | use Symfony\Component\OptionsResolver\OptionsResolver; |
| 31 | +use Symfony\Contracts\Translation\TranslatorInterface; |
31 | 32 |
|
32 | 33 | class APIKeyType extends AbstractType |
33 | 34 | { |
| 35 | + public function __construct(private readonly TranslatorInterface $translator) |
| 36 | + { |
| 37 | + } |
| 38 | + |
34 | 39 | public function getParent(): string |
35 | 40 | { |
36 | 41 | return PasswordType::class; |
37 | 42 | } |
38 | 43 |
|
39 | 44 | public function buildView(FormView $view, FormInterface $form, array $options): void |
40 | 45 | { |
41 | | - //Ensure that the field is never empty |
42 | | - $view->vars['value'] = $form->getViewData(); |
| 46 | + $viewData = $form->getViewData(); |
| 47 | + |
| 48 | + //If the field is disabled, show the redacted API key |
| 49 | + if ($options['disabled'] ?? false) { |
| 50 | + if ($viewData === null || $viewData === '') { |
| 51 | + $view->vars['value'] = $viewData; |
| 52 | + } else { |
| 53 | + |
| 54 | + $view->vars['value'] = self::redact((string)$viewData) . ' (' . $this ->translator->trans("form.apikey.redacted") . ')'; |
| 55 | + } |
| 56 | + } else { //Otherwise, show the actual value |
| 57 | + $view->vars['value'] = $viewData; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + public static function redact(string $apiKey): string |
| 62 | + { |
| 63 | + //Show only the last 2 characters of the API key if it is long enough (more than 16 characters) |
| 64 | + //Replace all other characters with dots |
| 65 | + if (strlen($apiKey) > 16) { |
| 66 | + return str_repeat('*', strlen($apiKey) - 2) . substr($apiKey, -2); |
| 67 | + } |
| 68 | + |
| 69 | + return str_repeat('*', strlen($apiKey)); |
43 | 70 | } |
44 | 71 |
|
45 | 72 | public function configureOptions(OptionsResolver $resolver): void |
|
0 commit comments