public function FacController::generateJson in Fast Autocomplete 8
Generates the Fast Autocomplete JSON for a search query.
Parameters
string $fac_config_id: The Fast Autocomplete configuration entity id.
string $langcode: The language code to generate the Json for.
string $hash: The hash to check.
string $key: The key to search with.
Return value
\Symfony\Component\HttpFoundation\JsonResponse The JSON response.
Throws
\Symfony\Component\HttpKernel\Exception\NotFoundHttpException
File
- src/
Controller/ FacController.php, line 120
Class
- FacController
- Fast Autocomplete controller class.
Namespace
Drupal\fac\ControllerCode
public function generateJson($fac_config_id, $langcode, $hash, $key) {
try {
// Check if the provided fac_config_id exists.
/** @var \Drupal\fac\Entity\FacConfig $fac_config */
if ($fac_config = $this->storage
->getStorage('fac_config')
->load($fac_config_id)) {
// Check if the specific Fast Autocomplete configuration is enabled.
if ($fac_config
->status()) {
$languages = $this->languageManager
->getLanguages();
// Check if the language code is valid.
if (in_array($langcode, array_keys($languages))) {
$response = NULL;
// Switch to the anonymous user if configured.
if ($fac_config
->anonymousSearch()) {
/** @var \Drupal\user\UserInterface $anonymous_user */
$anonymous_user = $this->storage
->getStorage('user')
->load(0);
$this->accountSwitcher
->switchTo($anonymous_user);
}
// Check if the hash is valid.
if ($this->hashService
->isValidHash($hash)) {
// Remove the .json part from the key.
$key = preg_replace('/\\.json$/', '', $key);
// Check the key length.
if (strlen($key) <= $fac_config
->getKeyMaxLength()) {
// Replace all underscores by spaces for the search key.
$search_key = preg_replace('/_/', ' ', $key);
// Get the search results.
$results['items'] = $this->searchService
->getResults($fac_config, $langcode, $search_key);
// Put the results in a json file in the public files folder.
$directory = PublicStream::basePath() . '/fac-json/' . $fac_config_id . '/' . $langcode . '/' . $this->hashService
->getHash();
if ($this->fileSystem
->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY)) {
$destination = $directory . '/' . $key . '.json';
$this->fileSystem
->saveData(json_encode($results), $destination, FileSystemInterface::EXISTS_REPLACE);
}
// Set the response.
$response = new JsonResponse($results);
}
}
// Switch back to the original user if switched to user 0.
if ($fac_config
->anonymousSearch()) {
$this->accountSwitcher
->switchBack();
}
if (!is_null($response)) {
return $response;
}
}
}
}
} catch (InvalidPluginDefinitionException $e) {
$this->logger
->error('An error occurred: ' . $e
->getMessage());
}
// If no response was returned, throw a NotFoundHttpException.
throw new NotFoundHttpException();
}