2021-11-23 14:08:50 +01:00

250 lines
8.6 KiB
PHP

<?php
/**
* 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\Controller;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Search\ParsingException;
use Chill\MainBundle\Search\SearchApi;
use Chill\MainBundle\Search\SearchApiNoQueryException;
use Chill\MainBundle\Search\SearchInterface;
use Chill\MainBundle\Search\SearchProvider;
use Chill\MainBundle\Search\UnknowSearchDomainException;
use Chill\MainBundle\Search\UnknowSearchNameException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Contracts\Translation\TranslatorInterface;
use function key;
use function reset;
/**
* Class SearchController.
*/
class SearchController extends AbstractController
{
protected PaginatorFactory $paginatorFactory;
protected SearchApi $searchApi;
protected SearchProvider $searchProvider;
protected TranslatorInterface $translator;
public function __construct(
SearchProvider $searchProvider,
TranslatorInterface $translator,
PaginatorFactory $paginatorFactory,
SearchApi $searchApi
) {
$this->searchProvider = $searchProvider;
$this->translator = $translator;
$this->paginatorFactory = $paginatorFactory;
$this->searchApi = $searchApi;
}
public function advancedSearchAction($name, Request $request)
{
try {
/* @var $variable Chill\MainBundle\Search\SearchProvider */
$searchProvider = $this->searchProvider;
/* @var $variable Chill\MainBundle\Search\HasAdvancedSearchFormInterface */
$search = $this->searchProvider
->getHasAdvancedFormByName($name);
} catch (\Chill\MainBundle\Search\UnknowSearchNameException $e) {
throw $this->createNotFoundException('no advanced search for '
. "{$name}");
}
if ($request->query->has('q')) {
$data = $search->convertTermsToFormData($searchProvider->parse(
$request->query->get('q')
));
}
$form = $this->createAdvancedSearchForm($name, $data ?? []);
if ($request->isMethod(Request::METHOD_POST)) {
$form->handleRequest($request);
if ($form->isValid()) {
$pattern = $this->searchProvider
->getHasAdvancedFormByName($name)
->convertFormDataToQuery($form->getData());
return $this->redirectToRoute('chill_main_search', [
'q' => $pattern, 'name' => $name,
]);
}
}
return $this->render(
'@ChillMain/Search/advanced_search.html.twig',
[
'form' => $form->createView(),
'name' => $name,
'title' => $search->getAdvancedSearchTitle(),
]
);
}
public function advancedSearchListAction(Request $request)
{
/* @var $variable Chill\MainBundle\Search\SearchProvider */
$searchProvider = $this->searchProvider;
$advancedSearchProviders = $searchProvider
->getHasAdvancedFormSearchServices();
if (\count($advancedSearchProviders) === 1) {
reset($advancedSearchProviders);
return $this->redirectToRoute('chill_main_advanced_search', [
'name' => key($advancedSearchProviders),
]);
}
return $this->render('@ChillMain/Search/choose_list.html.twig');
}
public function searchAction(Request $request, $_format)
{
$pattern = $request->query->get('q', '');
if ('' === $pattern) {
switch ($_format) {
case 'html':
return $this->render(
'@ChillMain/Search/error.html.twig',
[
'message' => $this->translator->trans('Your search is empty. '
. 'Please provide search terms.'),
'pattern' => $pattern,
]
);
case 'json':
return new JsonResponse([
'results' => [],
'pagination' => ['more' => false],
]);
}
}
$name = $request->query->get('name', null);
try {
if (null === $name) {
if ('json' === $_format) {
return new JsonResponse('Currently, we still do not aggregate results '
. 'from different providers', JsonResponse::HTTP_BAD_REQUEST);
}
// no specific search selected. Rendering result in "preview" mode
$results = $this->searchProvider
->getSearchResults(
$pattern,
0,
5,
[SearchInterface::SEARCH_PREVIEW_OPTION => true]
);
} else {
// we want search on a specific search provider. Display full results.
$results = [$this->searchProvider
->getResultByName(
$pattern,
$name,
$this->paginatorFactory->getCurrentPageFirstItemNumber(),
$this->paginatorFactory->getCurrentItemsPerPage(),
[
SearchInterface::SEARCH_PREVIEW_OPTION => false,
SearchInterface::REQUEST_QUERY_PARAMETERS => $request
->get(SearchInterface::REQUEST_QUERY_KEY_ADD_PARAMETERS, []),
],
$_format
), ];
if ('json' === $_format) {
return new JsonResponse(reset($results));
}
}
} catch (UnknowSearchDomainException $ex) {
return $this->render(
'@ChillMain/Search/error.html.twig',
[
'message' => $this->translator->trans('The domain %domain% '
. 'is unknow. Please check your search.', ['%domain%' => $ex->getDomain()]),
'pattern' => $pattern,
]
);
} catch (UnknowSearchNameException $ex) {
throw $this->createNotFoundException('The name ' . $ex->getName() . ' is not found');
} catch (ParsingException $ex) {
return $this->render(
'@ChillMain/Search/error.html.twig',
[
'message' => $this->translator->trans('Invalid terms') .
': ' . $this->translator->trans($ex->getMessage()),
'pattern' => $pattern,
]
);
}
return $this->render(
'@ChillMain/Search/list.html.twig',
['results' => $results, 'pattern' => $pattern]
);
}
public function searchApi(Request $request, $_format): JsonResponse
{
//TODO this is an incomplete implementation
$query = $request->query->get('q', '');
$types = $request->query->get('type', []);
if (count($types) === 0) {
throw new BadRequestException('The request must contains at '
. ' one type');
}
try {
$collection = $this->searchApi->getResults($query, $types, []);
} catch (SearchApiNoQueryException $e) {
throw new BadRequestHttpException($e->getMessage(), $e);
}
return $this->json($collection, \Symfony\Component\HttpFoundation\Response::HTTP_OK, [], ['groups' => ['read']]);
}
protected function createAdvancedSearchForm($name, array $data = [])
{
$builder = $this
->get('form.factory')
->createNamedBuilder(
null,
FormType::class,
$data,
['method' => Request::METHOD_POST]
);
$this->searchProvider
->getHasAdvancedFormByName($name)
->buildForm($builder);
$builder->add('submit', SubmitType::class, [
'label' => 'Search',
]);
return $builder->getForm();
}
}