Example #1
0
 /**
  * Return a model or collection based on the database result type
  */
 protected static function find(array $arrOptions)
 {
     $arrOptions['group'] = static::getTable() . '.id' . (null === $arrOptions['group'] ? '' : ', ' . $arrOptions['group']);
     $objProducts = parent::find($arrOptions);
     if (null === $objProducts) {
         return null;
     }
     $arrFilters = $arrOptions['filters'];
     $arrSorting = $arrOptions['sorting'];
     if (!empty($arrFilters) || !empty($arrSorting)) {
         $arrProducts = $objProducts->getModels();
         if (!empty($arrFilters)) {
             $arrProducts = array_filter($arrProducts, function ($objProduct) use($arrFilters) {
                 $arrGroups = array();
                 foreach ($arrFilters as $objFilter) {
                     $blnMatch = $objFilter->matches($objProduct);
                     if ($objFilter->hasGroup()) {
                         $arrGroups[$objFilter->getGroup()] = $arrGroups[$objFilter->getGroup()] ?: $blnMatch;
                     } elseif (!$blnMatch) {
                         return false;
                     }
                 }
                 if (!empty($arrGroups) && in_array(false, $arrGroups)) {
                     return false;
                 }
                 return true;
             });
         }
         // $arrProducts can be empty if the filter removed all records
         if (!empty($arrSorting) && !empty($arrProducts)) {
             $arrParam = array();
             $arrData = array();
             foreach ($arrSorting as $strField => $arrConfig) {
                 foreach ($arrProducts as $objProduct) {
                     // Both SORT_STRING and SORT_REGULAR are case sensitive, strings starting with a capital letter will come before strings starting with a lowercase letter.
                     // To perform a case insensitive search, force the sorting order to be determined by a lowercase copy of the original value.
                     // Temporary fix for price attribute (see #945)
                     if ($strField == 'price') {
                         $arrData[$strField][$objProduct->id] = $objProduct->getPrice() !== null ? $objProduct->getPrice()->getAmount() : 0;
                     } else {
                         $arrData[$strField][$objProduct->id] = strtolower(str_replace('"', '', $objProduct->{$strField}));
                     }
                 }
                 $arrParam[] =& $arrData[$strField];
                 $arrParam[] = $arrConfig[0];
                 $arrParam[] = $arrConfig[1];
             }
             // Add product array as the last item. This will sort the products array based on the sorting of the passed in arguments.
             $arrParam[] =& $arrProducts;
             call_user_func_array('array_multisort', $arrParam);
         }
         $objProducts = new \Model\Collection($arrProducts, static::$strTable);
     }
     return $objProducts;
 }