/**
  * Builds facets from all attributes present in the data set.
  * @param DataList|PaginatedList $matches
  * @return array
  */
 protected function buildAllAttributeFacets($matches)
 {
     $q = $matches instanceof PaginatedList ? $matches->getList()->dataQuery()->query() : $matches->dataQuery()->query();
     // this is the easiest way to get SiteTree vs SiteTree_Live
     $baseTable = $q->getFrom();
     if (is_array($baseTable)) {
         $baseTable = reset($baseTable);
     }
     $q = $q->setSelect(array())->selectField('"ProductAttributeType"."ID"', 'TypeID')->selectField('"ProductAttributeType"."Label"', 'TypeLabel')->selectField('"ProductAttributeValue"."ID"', 'Value')->selectField('"ProductAttributeValue"."Value"', 'Label')->selectField('count(distinct ' . $baseTable . '."ID")', 'Count')->selectField('"ProductAttributeValue"."Sort"')->addInnerJoin('Product_StaticAttributeTypes', $baseTable . '."ID" = "Product_StaticAttributeTypes"."ProductID"')->addInnerJoin('ProductAttributeType', '"Product_StaticAttributeTypes"."ProductAttributeTypeID" = "ProductAttributeType"."ID"')->addInnerJoin('Product_StaticAttributeValues', $baseTable . '."ID" = "Product_StaticAttributeValues"."ProductID"')->addInnerJoin('ProductAttributeValue', '"Product_StaticAttributeValues"."ProductAttributeValueID" = "ProductAttributeValue"."ID"' . ' AND "ProductAttributeValue"."TypeID" = "ProductAttributeType"."ID"')->setOrderBy(array('"ProductAttributeType"."Label"' => 'ASC', '"ProductAttributeValue"."Sort"' => 'ASC'))->setGroupBy(array('"ProductAttributeValue"."ID"', '"ProductAttributeType"."ID"'))->execute();
     $curType = 0;
     $facets = array();
     $curFacet = null;
     foreach ($q as $row) {
         if ($curType != $row['TypeID']) {
             if ($curType > 0) {
                 $facets['ATT' . $curType] = $curFacet;
             }
             $curType = $row['TypeID'];
             $curFacet = array('Label' => $row['TypeLabel'], 'Source' => 'ATT' . $curType, 'Type' => ShopSearch::FACET_TYPE_LINK, 'Values' => array());
         }
         unset($row['TypeID']);
         unset($row['TypeLabel']);
         $curFacet['Values'][$row['Value']] = new ArrayData($row);
     }
     if ($curType > 0) {
         $facets['ATT' . $curType] = $curFacet;
     }
     return $facets;
 }