Skip to content

Commit

Permalink
Order search facets by count, name (#3802)
Browse files Browse the repository at this point in the history
  • Loading branch information
dafeder committed Jul 6, 2022
1 parent 11d6ccd commit 04653f9
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
25 changes: 23 additions & 2 deletions modules/metastore/modules/metastore_search/src/Search.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,16 +138,37 @@ public function facets(array $params = []) : array {
$facets = $this->getFacetsFromIndex($params, $this->index, $query);
}

static::orderFacets($facets);
return $facets;
}

/**
* Order the facet array by total (desc) then name (asc)
*
* @param array $facets
* Array of facet objects with properties "total", "name" and "type".
*/
public static function orderFacets(array &$facets): void {
usort($facets, function ($a, $b) {
if (!isset($a->name, $b->name, $a->total, $b->total)) {
throw new \InvalidArgumentException("Facets much name and total properties.");
}
if ($a->total == $b->total) {
return strcmp($a->name, $b->name);
}
else {
return $b->total - $a->total;
}
});
}

/**
* Private.
*
* @param \Drupal\search_api\Query\ResultSet $result
* Result set.
*
* @return array
* @return null|array
* Filtered results.
*/
private function getData(ResultSet $result) {
Expand All @@ -158,7 +179,7 @@ function ($item) use ($metastore) {
$id = $item->getId();
$id = str_replace('dkan_dataset/', '', $id);
try {
return json_decode($metastore->get('dataset', $id));
return json_decode((string) $metastore->get('dataset', $id));
}
catch (\Exception $e) {
return NULL;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,41 @@ public function testSearchParameterWithComma() {
);
}

/**
* Test the Service::orderFacets method.
*/
public function testOrderFacets() {
$in = [
(object) ['name' => 'Ana', 'total' => 1],
(object) ['name' => 'Bob', 'total' => 2],
(object) ['name' => 'Chris', 'total' => 3],
(object) ['name' => 'Dana', 'total' => 3],
(object) ['name' => 'Ed', 'total' => 3],
];

// orderFacets() should order descending by count, then ascending by name.
$out = [
(object) ['name' => 'Chris', 'total' => 3],
(object) ['name' => 'Dana', 'total' => 3],
(object) ['name' => 'Ed', 'total' => 3],
(object) ['name' => 'Bob', 'total' => 2],
(object) ['name' => 'Ana', 'total' => 1],
];

Search::orderFacets($in);

$this->assertEquals($out, $in);

$no_name = [
(object) ['field1' => 'foo', 'field2' => 'bar'],
(object) ['field1' => 'x', 'field2' => 'y'],
];

// Passing facets without name or total properties will throw exception.
$this->expectException(\InvalidArgumentException::class);
Search::orderFacets($no_name);
}

/**
* Test for facets().
*/
Expand Down

0 comments on commit 04653f9

Please sign in to comment.