Exemple #1
0
 /**
  * Filters a collection and return data filtered by request
  *
  * @param mixed           $collection
  * @param FilterInterface $filter
  * @param array           $fieldMap
  * @return array
  * @throws \UnexpectedValueException Se não encontrar o Incorporator
  * @throws \Exception                Se houver algum erro
  */
 public function filter($collection, FilterInterface $filter, array $fieldMap = array())
 {
     if (is_array($collection)) {
         $collection = new ArrayCollection($collection);
     }
     try {
         $incorporator = $this->incorporatorFactory->getIncorporator($collection);
     } catch (\RuntimeException $e) {
         throw new \UnexpectedValueException('Collection inválido', $e->getCode(), $e);
     }
     if ($incorporator instanceof JoinableIncorporatorInterface) {
         $incorporator->setFieldMap($fieldMap);
     }
     try {
         if ($filter instanceof TotalizableInterface) {
             switch ($totalizableMode = $this->totalizableMode) {
                 case IncorporatorInterface::TOTALIZABLE_ALL:
                 case IncorporatorInterface::TOTALIZABLE_ONLY_FILTERED:
                     $totalFiltered = $incorporator->count($collection, $filter->createFilterForTotalFilteredRecords());
                     if ($totalizableMode === IncorporatorInterface::TOTALIZABLE_ALL) {
                         // faz mais uma busca para trazer o total sem filtro
                         $total = $incorporator->count($collection, $filter->createFilterForTotalRecords());
                     } else {
                         $total = $totalFiltered;
                     }
                     $filter->setTotalRecords($total, $totalFiltered);
                     unset($totalCollection);
                     break;
                 case IncorporatorInterface::TOTALIZABLE_UNKNOWN:
                     $filter->setTotalRecords($filter->getFirstResult() + $filter->getMaxResults() + 1);
                     break;
             }
         }
     } catch (\Exception $e) {
         if ($filter instanceof ErrorInformableInterface) {
             $filter->setErrorMessage($e->getMessage());
         } else {
             throw $e;
         }
     }
     return $filter->getOutputResponse($incorporator->incorporate($collection, $filter));
 }