/**
  * {@inheritDoc}
  */
 public function search(Request $request)
 {
     $query = $request->getContent();
     // Set default query parameters
     if (!isset($query['page'])) {
         $query['page'] = null;
     }
     if (!isset($query['per_page'])) {
         $query['per_page'] = null;
     }
     if (!isset($query['limit'])) {
         $query['limit'] = null;
     }
     if (!isset($query['offset'])) {
         $query['offset'] = null;
     }
     if (!isset($query['sort_by'])) {
         $query['sort_by'] = null;
     }
     if (isset($query['sort_order']) && in_array(strtoupper($query['sort_order']), ['ASC', 'DESC'])) {
         $query['sort_order'] = strtoupper($query['sort_order']);
     } else {
         $query['sort_order'] = 'ASC';
     }
     // Begin building the search query.
     $entityClass = $this->getEntityClass();
     $qb = $this->getEntityManager()->createQueryBuilder()->select($entityClass)->from($entityClass, $entityClass);
     $this->buildQuery($qb, $query);
     $qb->groupBy("{$entityClass}.id");
     // Trigger the search.query event.
     $event = new Event(Event::API_SEARCH_QUERY, $this, ['services' => $this->getServiceLocator(), 'queryBuilder' => $qb, 'request' => $request]);
     $this->getEventManager()->trigger($event);
     // Get the total results.
     $totalResultsQb = clone $qb;
     $totalResults = $totalResultsQb->resetDQLPart('groupBy')->select("COUNT(DISTINCT {$entityClass}.id)")->getQuery()->getSingleScalarResult();
     // Do not make the request if the max results (limit) is 0. Useful if
     // the only information needed is total results.
     $representations = [];
     if ($qb->getMaxResults() || null === $qb->getMaxResults()) {
         // Finish building the search query. In addition to any sorting the
         // adapters add, always sort by entity ID.
         $this->sortQuery($qb, $query);
         $qb->addOrderBy("{$entityClass}.id", $query['sort_order']);
         $this->limitQuery($qb, $query);
         foreach ($qb->getQuery()->getResult() as $entity) {
             $representations[] = $this->getRepresentation($entity);
         }
     }
     $response = new Response($representations);
     $response->setTotalResults($totalResults);
     return $response;
 }