uri = $uri; $this->credentials = $credentials; } /** * Perform a facet query * @param string query the query to execute * @param array fields the list of fields to facet on * @param in top the number of facet results to return * @return HttpResponse */ function facets($query, $fields, $top = 10) { if (! isset( $this->request_factory) ) { $this->request_factory = new HttpRequestFactory(); } $uri = $this->uri . '?query=' . urlencode($query) . '&fields=' . urlencode(join(' ', $fields)) . '&top=' . urlencode($top) . '&output=xml'; $request = $this->request_factory->make( 'GET', $uri , $this->credentials ); $request->set_accept(MIME_XML); return $request->execute(); } /** * Perform a facet query and return the results as an array. An empty array is returned if there are any HTTP errors. * @param string query the query to execute * @param array fields the list of fields to facet on * @param in top the number of facet results to return * @return array see parse_facet_xml for the structure of this array */ function facets_to_array($query, $fields, $top = 10) { $facets = array(); $response = $this->facets($query, $fields, $top); if ($response->is_success()) { $facets = $this->parse_facet_xml($response->body); } return $facets; } /** * Parse the response from a facet query into an array. * This method returns an associative array where the keys correspond to field name and the values are * associative arrays with two keys: * * @param string xml the facet response as an XML document * @return array */ function parse_facet_xml($xml) { $facets = array(); $reader = new XMLReader(); $reader->XML($xml); $field_terms = array(); $field_name = ''; while ($reader->read()) { if ( $reader->name == 'field') { if ( $reader->nodeType == XMLReader::ELEMENT) { $field_terms = array(); $field_name = $reader->getAttribute("name"); } elseif ( $reader->nodeType == XMLReader::END_ELEMENT) { $facets[$field_name] = $field_terms; $field_terms = array(); } } elseif ( $reader->name == 'term') { if ( $reader->nodeType == XMLReader::ELEMENT) { $term = array(); $term['value'] = $reader->getAttribute("value"); $term['number'] = $reader->getAttribute("number"); $field_terms[] = $term; } } } $reader->close(); return $facets; } } ?>