jsonResponse([]); } $limit = min(100, max(1, $limit)); $searchTypes = $this->resolveTypes($types); $results = []; foreach ($searchTypes as $type) { $results = array_merge($results, match ($type) { 'machine' => $this->searchWithReference($this->machines, 'm', 'machine', $query), 'piece' => $this->searchWithReference($this->pieces, 'p', 'piece', $query), 'composant' => $this->searchWithReference($this->composants, 'c', 'composant', $query), 'product' => $this->searchWithReference($this->products, 'p', 'product', $query), 'site' => $this->searchNameOnly($this->sites, 's', 'site', $query), 'constructeur' => $this->searchNameOnly($this->constructeurs, 'c', 'constructeur', $query), }); } $results = array_slice($results, 0, $limit); return $this->jsonResponse($results); } /** * @return list */ private function resolveTypes(string $types): array { if ('' === trim($types)) { return self::ALLOWED_TYPES; } $requested = array_map('trim', explode(',', strtolower($types))); return array_values(array_intersect($requested, self::ALLOWED_TYPES)); } private function searchWithReference(object $repository, string $alias, string $type, string $search): array { $qb = $repository->createQueryBuilder($alias) ->select("{$alias}.id", "{$alias}.name", "{$alias}.reference") ->where("LOWER({$alias}.name) LIKE LOWER(:search)") ->orWhere("LOWER({$alias}.reference) LIKE LOWER(:search)") ->setParameter('search', "%{$search}%") ->orderBy("{$alias}.name", 'ASC') ; $rows = $qb->getQuery()->getArrayResult(); return array_map(fn (array $row) => [ 'type' => $type, 'id' => $row['id'], 'name' => $row['name'], 'reference' => $row['reference'] ?? null, ], $rows); } private function searchNameOnly(object $repository, string $alias, string $type, string $search): array { $qb = $repository->createQueryBuilder($alias) ->select("{$alias}.id", "{$alias}.name") ->where("LOWER({$alias}.name) LIKE LOWER(:search)") ->setParameter('search', "%{$search}%") ->orderBy("{$alias}.name", 'ASC') ; $rows = $qb->getQuery()->getArrayResult(); return array_map(fn (array $row) => [ 'type' => $type, 'id' => $row['id'], 'name' => $row['name'], 'reference' => null, ], $rows); } }