Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.62% covered (success)
97.62%
41 / 42
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
SearchEntitiesEndpoint
97.62% covered (success)
97.62%
41 / 42
0.00% covered (danger)
0.00%
0 / 1
10
0.00% covered (danger)
0.00%
0 / 1
 handle
97.62% covered (success)
97.62%
41 / 42
0.00% covered (danger)
0.00%
0 / 1
10
1<?php
2
3namespace Olz\Common\Endpoints;
4
5use Doctrine\Common\Collections\Criteria;
6use Olz\Api\OlzTypedEndpoint;
7use Olz\Entity\Common\OlzEntity;
8use Olz\Entity\Faq\Question;
9use Olz\Entity\Faq\QuestionCategory;
10use Olz\Entity\Roles\Role;
11use Olz\Entity\Service\Download;
12use Olz\Entity\Service\Link;
13use Olz\Entity\SolvEvent;
14use Olz\Entity\Termine\Termin;
15use Olz\Entity\Termine\TerminLabel;
16use Olz\Entity\Termine\TerminLocation;
17use Olz\Entity\Termine\TerminTemplate;
18use Olz\Entity\Users\User;
19use PhpTypeScriptApi\HttpError;
20
21/**
22 * TODO: Support key-of<self::SUPPORTED_ENTITY_TYPES> in php-typescript-api.
23 *
24 * @phpstan-type OlzEntityResult array{
25 *   id: int<1, max>,
26 *   title: non-empty-string,
27 * }
28 * @phpstan-type OlzSearchableEntityType 'Download'|'Link'|'Question'|'QuestionCategory'|'SolvEvent'|'Termin'|'TerminLabel'|'TerminLocation'|'TerminTemplate'|'Role'|'User'
29 *
30 * @extends OlzTypedEndpoint<
31 *   array{
32 *     entityType: OlzSearchableEntityType,
33 *     query?: ?string,
34 *     id?: ?int<1, max>,
35 *     filter?: ?array<string, string>,
36 *   },
37 *   array{
38 *     result: array<OlzEntityResult>
39 *   }
40 * >
41 */
42class SearchEntitiesEndpoint extends OlzTypedEndpoint {
43    public const SUPPORTED_ENTITY_TYPES = [
44        'Download' => Download::class,
45        'Link' => Link::class,
46        'Question' => Question::class,
47        'QuestionCategory' => QuestionCategory::class,
48        'SolvEvent' => SolvEvent::class,
49        'Termin' => Termin::class,
50        'TerminLabel' => TerminLabel::class,
51        'TerminLocation' => TerminLocation::class,
52        'TerminTemplate' => TerminTemplate::class,
53        'Role' => Role::class,
54        'User' => User::class,
55    ];
56
57    protected function handle(mixed $input): mixed {
58        $entity_type = $input['entityType'];
59        if ($entity_type !== 'Termin') { // Anonymous User creating NewsEntry with terminId
60            $this->checkPermission('any');
61        }
62        $entity_class = self::SUPPORTED_ENTITY_TYPES[$entity_type];
63
64        $filter_criteria = [];
65        foreach ($input['filter'] ?? [] as $key => $value) {
66            try {
67                $filter_criteria[] = $entity_class::getCriteriaForFilter($key, $value);
68            } catch (\Throwable $th) {
69                throw new HttpError(400, "Invalid filter {$key} => {$value} for entity {$entity_type}: {$th->getMessage()}");
70            }
71        }
72
73        $search_terms = preg_split('/\s+/', $input['query'] ?? '') ?: [];
74        $matching_criterium = Criteria::expr()->andX(
75            ...array_map(function ($search_term) use ($entity_class) {
76                return $entity_class::getCriteriaForQuery($search_term);
77            }, $search_terms),
78        );
79
80        $id = $input['id'] ?? null;
81        $id_field_name = $entity_class::getIdFieldNameForSearch();
82        $id_criteria = $id ? [Criteria::expr()->eq($id_field_name, $id)] : [];
83
84        $repo = $this->entityManager()->getRepository($entity_class);
85        $not_deleted_criteria = is_subclass_of($entity_class, OlzEntity::class) ? [
86            Criteria::expr()->isNull('deleted_at'),
87        ] : [];
88        $criteria = Criteria::create()
89            ->where(Criteria::expr()->andX(
90                $matching_criterium,
91                ...$not_deleted_criteria,
92                ...$filter_criteria,
93                ...$id_criteria,
94            ))
95            ->setFirstResult(0)
96            ->setMaxResults(10)
97        ;
98        $matching_entities = $repo->matching($criteria);
99
100        $result = [];
101        foreach ($matching_entities as $entity) {
102            if ($entity->getIdForSearch() <= 0 || !$entity->getTitleForSearch()) {
103                continue;
104            }
105            $result[] = [
106                'id' => $entity->getIdForSearch(),
107                'title' => $entity->getTitleForSearch(),
108            ];
109        }
110
111        return ['result' => $result];
112    }
113}