Skip to content

Commit

Permalink
[Autocomplete] Add handling extra options in the EntityAutocompleteCo…
Browse files Browse the repository at this point in the history
…ntroller
  • Loading branch information
jakubtobiasz committed Dec 3, 2023
1 parent 90f57b3 commit 3d24e75
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/Autocomplete/src/Controller/EntityAutocompleteController.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,20 @@
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\UX\Autocomplete\AutocompleteResultsExecutor;
use Symfony\UX\Autocomplete\AutocompleterRegistry;
use Symfony\UX\Autocomplete\Calculator\ChecksumCalculatorInterface;

/**
* @author Ryan Weaver <[email protected]>
*/
final class EntityAutocompleteController
{
public const EXTRA_OPTIONS = 'extra_options';

public function __construct(
private AutocompleterRegistry $autocompleteFieldRegistry,
private AutocompleteResultsExecutor $autocompleteResultsExecutor,
private UrlGeneratorInterface $urlGenerator,
private ChecksumCalculatorInterface $checksumCalculator,
) {
}

Expand All @@ -38,6 +42,11 @@ public function __invoke(string $alias, Request $request): Response
throw new NotFoundHttpException(sprintf('No autocompleter found for "%s". Available autocompleters are: (%s)', $alias, implode(', ', $this->autocompleteFieldRegistry->getAutocompleterNames())));
}

$extraOptions = $this->getExtraOptions($request);
$autocompleter = $autocompleter->withOptions([
'extra_options' => $extraOptions,
]);

$page = $request->query->getInt('page', 1);
$nextPage = null;

Expand All @@ -54,4 +63,26 @@ public function __invoke(string $alias, Request $request): Response
'next_page' => $nextPage,
]);
}

/**
* @return array<string, scalar|array|null>
*/
private function getExtraOptions(Request $request): array
{
// TODO: This method should be refactored
if (!$request->query->has(self::EXTRA_OPTIONS)) {
return [];
}

/** @var array $extraOptions */
$extraOptions = json_decode(base64_decode($request->query->get(self::EXTRA_OPTIONS)), true);
$checksum = $extraOptions['@checksum'] ?? null;
unset($extraOptions['@checksum']);

if ($checksum !== $this->checksumCalculator->calculateForArray($extraOptions)) {
throw new \InvalidArgumentException('The extra options have been tampered with.');
}

return $extraOptions;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ private function registerBasicServices(ContainerBuilder $container): void
new Reference('ux.autocomplete.autocompleter_registry'),
new Reference('ux.autocomplete.results_executor'),
new Reference('router'),
new Reference('ux.autocomplete.checksum_calculator'),
])
->addTag('controller.service_arguments')
;
Expand Down

0 comments on commit 3d24e75

Please sign in to comment.