You are here

public function FacetsSerializer::render in Facets 8

Render the display in this style.

Overrides Serializer::render

File

modules/facets_rest/src/Plugin/views/style/FacetsSerializer.php, line 81

Class

FacetsSerializer
The style plugin for serialized output formats.

Namespace

Drupal\facets_rest\Plugin\views\style

Code

public function render() {
  $rows = [];

  // If the Data Entity row plugin is used, this will be an array of entities
  // which will pass through Serializer to one of the registered Normalizers,
  // which will transform it to arrays/scalars. If the Data field row plugin
  // is used, $rows will not contain objects and will pass directly to the
  // Encoder.
  foreach ($this->view->result as $row_index => $row) {

    // Keep track of the current rendered row, like every style plugin has to
    // do.
    // @see \Drupal\views\Plugin\views\style\StylePluginBase::renderFields
    $this->view->row_index = $row_index;
    $rows['search_results'][] = $this->view->rowPlugin
      ->render($row);
  }
  unset($this->view->row_index);

  // Get the content type configured in the display or fallback to the
  // default.
  if (empty($this->view->live_preview)) {
    $content_type = $this->displayHandler
      ->getContentType();
  }
  else {
    $content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json';
  }

  // Processing facets.
  $facetsource_id = "search_api:views_rest__{$this->view->id()}__{$this->view->getDisplay()->display['id']}";
  $facets = $this->facetsManager
    ->getFacetsByFacetSourceId($facetsource_id);
  $this->facetsManager
    ->updateResults($facetsource_id);
  $processed_facets = [];
  $facets_metadata = [];
  foreach ($facets as $facet) {
    $processed_facets[] = $this->facetsManager
      ->build($facet);
    $facets_metadata[$facet
      ->id()] = array(
      'label' => $facet
        ->label(),
      'weight' => $facet
        ->getWeight(),
      'field_id' => $facet
        ->getFieldIdentifier(),
      'url_alias' => $facet
        ->getUrlAlias(),
    );
  }
  uasort($facets_metadata, function ($a, $b) {
    return $a['weight'] > $b['weight'];
  });
  $rows['facets'] = array_values($processed_facets);
  $rows['facets_metadata'] = $facets_metadata;
  if (!$this->options['show_facets']) {
    $rows = $rows['search_results'];
  }
  return $this->serializer
    ->serialize($rows, $content_type, [
    'views_style_plugin' => $this,
  ]);
}