JsonApiResponseWidget.php in JSON:API Search API 8
File
modules/jsonapi_search_api_facets/src/Plugin/facets/widget/JsonApiResponseWidget.php
View source
<?php
namespace Drupal\jsonapi_search_api_facets\Plugin\facets\widget;
use Drupal\facets\FacetInterface;
use Drupal\facets\Result\ResultInterface;
use Drupal\facets\Widget\WidgetPluginBase;
class JsonApiResponseWidget extends WidgetPluginBase {
public function build(FacetInterface $facet) {
$build = [
'id' => $facet
->id(),
'label' => $facet
->getName(),
'path' => $facet
->getUrlAlias(),
'terms' => [],
];
$configuration = $facet
->getWidget();
$this->showNumbers = empty($configuration['show_numbers']) ? FALSE : (bool) $configuration['show_numbers'];
foreach ($facet
->getResults() as $result) {
if ($result
->getUrl() === NULL) {
$build['terms'][] = $this
->generateValues($result);
}
else {
$build['terms'][] = $this
->buildListItems($facet, $result);
}
}
return $build;
}
protected function buildListItems(FacetInterface $facet, ResultInterface $result) {
if ($children = $result
->getChildren()) {
$items = $this
->prepare($result);
$children_markup = [];
foreach ($children as $child) {
$children_markup[] = $this
->buildChildren($child);
}
$items['children'] = [
$children_markup,
];
}
else {
$items = $this
->prepare($result);
}
return $items;
}
protected function prepare(ResultInterface $result) {
$values = $this
->generateValues($result);
$url = $result
->getUrl();
if ($url === NULL) {
$facet_values = $values;
}
else {
$facet_values['url'] = $url
->setAbsolute(TRUE)
->toString(TRUE)
->getGeneratedUrl();
$facet_values['values'] = $values;
}
return $facet_values;
}
protected function buildChildren(ResultInterface $child) {
$values = $this
->generateValues($child);
$url = $child
->getUrl();
if ($url !== NULL) {
$facet_values['url'] = $url
->setAbsolute(TRUE)
->toString(TRUE)
->getGeneratedUrl();
$facet_values['values'] = $values;
}
else {
$facet_values = $values;
}
return $facet_values;
}
protected function generateValues(ResultInterface $result) {
$values = [
'value' => $result
->getRawValue(),
'label' => $result
->getDisplayValue(),
'active' => $result
->isActive(),
];
if ($this->configuration['show_numbers']) {
$values['count'] = (int) $result
->getCount();
}
return $values;
}
}