View source
<?php
namespace Drupal\facets_rest\Plugin\views\style;
use Drupal\Core\Form\FormStateInterface;
use Drupal\facets\FacetManager\DefaultFacetManager;
use Drupal\rest\Plugin\views\style\Serializer;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Serializer\SerializerInterface;
class FacetsSerializer extends Serializer {
protected $facetsManager;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('serializer'), $container
->getParameter('serializer.formats'), $container
->getParameter('serializer.format_providers'), $container
->get('facets.manager'));
}
public function __construct(array $configuration, $plugin_id, $plugin_definition, SerializerInterface $serializer, array $serializer_formats, array $serializer_format_providers, DefaultFacetManager $facets_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer, $serializer_formats, $serializer_format_providers);
$this->facetsManager = $facets_manager;
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['show_facets'] = [
'default' => TRUE,
];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['show_facets'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Show facets in the output'),
'#default_value' => $this->options['show_facets'],
];
}
public function render() {
$rows = [];
foreach ($this->view->result as $row_index => $row) {
$this->view->row_index = $row_index;
$rows['search_results'][] = $this->view->rowPlugin
->render($row);
}
unset($this->view->row_index);
if (empty($this->view->live_preview)) {
$content_type = $this->displayHandler
->getContentType();
}
else {
$content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json';
}
$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,
]);
}
}