Facet.php 22.4 KB
Newer Older
Nick_vh's avatar
Nick_vh committed
1 2
<?php

3
namespace Drupal\facets\Entity;
Nick_vh's avatar
Nick_vh committed
4 5

use Drupal\Core\Config\Entity\ConfigEntityBase;
6
use Drupal\Core\Entity\EntityStorageInterface;
7 8
use Drupal\facets\Exception\Exception;
use Drupal\facets\Exception\InvalidProcessorException;
9
use Drupal\facets\FacetInterface;
Nick_vh's avatar
Nick_vh committed
10 11

/**
12
 * Defines the facet configuration entity.
Nick_vh's avatar
Nick_vh committed
13 14
 *
 * @ConfigEntityType(
15
 *   id = "facets_facet",
Nick_vh's avatar
Nick_vh committed
16 17 18
 *   label = @Translation("Facet"),
 *   handlers = {
 *     "storage" = "Drupal\Core\Config\Entity\ConfigEntityStorage",
19
 *     "list_builder" = "Drupal\facets\FacetListBuilder",
Nick_vh's avatar
Nick_vh committed
20
 *     "form" = {
21
 *       "default" = "Drupal\facets\Form\FacetSettingsForm",
22
 *       "edit" = "Drupal\facets\Form\FacetForm",
23
 *       "settings" = "Drupal\facets\Form\FacetSettingsForm",
24
 *       "clone" = "Drupal\facets\Form\FacetCloneForm",
25
 *       "delete" = "Drupal\Core\Entity\EntityDeleteForm",
Nick_vh's avatar
Nick_vh committed
26 27
 *     },
 *   },
28
 *   admin_permission = "administer facets",
Nick_vh's avatar
Nick_vh committed
29 30 31 32 33
 *   config_prefix = "facet",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "uuid" = "uuid",
34 35
 *     "status" = "status",
 *     "weight" = "weight"
Nick_vh's avatar
Nick_vh committed
36 37 38 39
 *   },
 *   config_export = {
 *     "id",
 *     "name",
40
 *     "url_alias",
41
 *     "weight",
42
 *     "min_count",
43
 *     "show_only_one_result",
44
 *     "field_identifier",
45
 *     "facet_source_id",
borisson_'s avatar
borisson_ committed
46
 *     "widget",
47
 *     "query_operator",
48 49 50
 *     "use_hierarchy",
 *     "expand_hierarchy",
 *     "enable_parent_when_child_gets_disabled",
51
 *     "hard_limit",
52
 *     "exclude",
53
 *     "only_visible_when_facet_source_is_visible",
54
 *     "processor_configs",
55
 *     "empty_behavior"
Nick_vh's avatar
Nick_vh committed
56 57
 *   },
 *   links = {
58
 *     "collection" = "/admin/config/search/facets",
mr.baileys's avatar
mr.baileys committed
59 60
 *     "add-form" = "/admin/config/search/facets/add-facet",
 *     "edit-form" = "/admin/config/search/facets/{facets_facet}/edit",
61
 *     "settings-form" = "/admin/config/search/facets/{facets_facet}/settings",
62
 *     "clone-form" = "/admin/config/search/facets/{facets_facet}/clone",
mr.baileys's avatar
mr.baileys committed
63
 *     "delete-form" = "/admin/config/search/facets/{facets_facet}/delete",
Nick_vh's avatar
Nick_vh committed
64 65 66 67 68 69
 *   }
 * )
 */
class Facet extends ConfigEntityBase implements FacetInterface {

  /**
70
   * The ID of the facet.
Nick_vh's avatar
Nick_vh committed
71 72 73 74 75 76
   *
   * @var string
   */
  protected $id;

  /**
77
   * A name to be displayed for the facet.
Nick_vh's avatar
Nick_vh committed
78 79 80 81 82
   *
   * @var string
   */
  protected $name;

83 84 85 86 87 88 89
  /**
   * The name for the parameter when used in the URL.
   *
   * @var string
   */
  protected $url_alias;

Nick_vh's avatar
Nick_vh committed
90
  /**
91
   * A string describing the facet.
Nick_vh's avatar
Nick_vh committed
92 93 94 95 96
   *
   * @var string
   */
  protected $description;

borisson_'s avatar
borisson_ committed
97
  /**
98
   * The widget plugin definition.
borisson_'s avatar
borisson_ committed
99
   *
100
   * @var array
borisson_'s avatar
borisson_ committed
101 102 103
   */
  protected $widget;

104
  /**
105
   * The widget plugin instance.
106
   *
107
   * @var \Drupal\facets\Widget\WidgetPluginBase
108
   */
109
  protected $widgetInstance;
110

111 112 113 114 115 116 117 118 119 120 121 122 123 124
  /**
   * The hierarchy definition.
   *
   * @var array
   */
  protected $hierarchy;

  /**
   * The hierarchy instance.
   *
   * @var \Drupal\facets\Hierarchy\HierarchyPluginBase
   */
  protected $hierarchy_processor;

Nick_vh's avatar
Nick_vh committed
125
  /**
126
   * The operator to hand over to the query, currently AND | OR.
Nick_vh's avatar
Nick_vh committed
127
   *
128
   * @var string
Nick_vh's avatar
Nick_vh committed
129
   */
130
  protected $query_operator;
Nick_vh's avatar
Nick_vh committed
131

132
  /**
133 134
   * Hard limit for the facet items.
   *
135
   * @var int
136 137 138 139 140
   */
  protected $hard_limit;

  /**
   * A boolean flag indicating if search should exclude selected facets.
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
   *
   * @var bool
   */
  protected $use_hierarchy = FALSE;

  /**
   * A boolean indicating if hierarchical items should always be expanded.
   *
   * @var bool
   */
  protected $expand_hierarchy = FALSE;

  /**
   * Wether or not parents should be enabled when a child gets disabled.
   *
   * @var bool
   */
  protected $enable_parent_when_child_gets_disabled = TRUE;

160
  /**
borisson_'s avatar
borisson_ committed
161
   * A boolean flag indicating if search should exclude selected facets.
162 163 164 165 166
   *
   * @var bool
   */
  protected $exclude;

167 168 169 170 171
  /**
   * The field identifier.
   *
   * @var string
   */
172
  protected $field_identifier;
173

174
  /**
175
   * The id of the facet source.
176 177 178
   *
   * @var string
   */
179
  protected $facet_source_id;
180

181 182 183
  /**
   * The facet source belonging to this facet.
   *
184
   * @var \Drupal\facets\FacetSource\FacetSourcePluginInterface
185 186 187
   *
   * @see getFacetSource()
   */
188
  protected $facet_source_instance = NULL;
189

190 191 192 193 194 195 196
  /**
   * The path all the links should point to.
   *
   * @var string
   */
  protected $path;

Jur de Vries's avatar
Jur de Vries committed
197 198 199
  /**
   * The results.
   *
200
   * @var \Drupal\facets\Result\ResultInterface[]
Jur de Vries's avatar
Jur de Vries committed
201
   */
marthinal's avatar
marthinal committed
202
  protected $results = [];
Jur de Vries's avatar
Jur de Vries committed
203

204 205 206 207 208
  /**
   * An array of active values.
   *
   * @var string[]
   */
marthinal's avatar
marthinal committed
209
  protected $active_values = [];
210

211 212 213 214 215 216 217
  /**
   * An array containing the facet source plugins.
   *
   * @var array
   */
  protected $facetSourcePlugins;

218 219 220
  /**
   * Cached information about the processors available for this facet.
   *
221
   * @var \Drupal\facets\Processor\ProcessorInterface[]|null
222 223 224 225
   *
   * @see loadProcessors()
   */
  protected $processors;
226

227 228 229 230 231
  /**
   * Configuration for the processors. This is an array of arrays.
   *
   * @var array
   */
232
  protected $processor_configs = [];
233

234
  /**
borisson_'s avatar
borisson_ committed
235 236
   * Is the facet only visible when the facet source is only visible.
   *
237 238 239
   * A boolean that defines whether or not the facet is only visible when the
   * facet source is visible.
   *
240
   * @var bool
241 242 243
   */
  protected $only_visible_when_facet_source_is_visible;

244 245 246 247 248 249 250
  /**
   * Determines if only one result can be selected in the facet at one time.
   *
   * @var bool
   */
  protected $show_only_one_result = FALSE;

251 252 253
  /**
   * The no-result configuration.
   *
254
   * @var string[]
255 256 257
   */
  protected $empty_behavior;

258
  /**
borisson_'s avatar
borisson_ committed
259
   * The widget plugin manager.
260
   *
261
   * @var \Drupal\facets\Widget\WidgetPluginManager
262 263 264
   */
  protected $widget_plugin_manager;

265 266 267 268 269 270 271 272
  /**
   * The hierarchy plugin manager.
   *
   * @var \Drupal\facets\Hierarchy\HierarchyPluginManager
   *   The hierarchy plugin manager.
   */
  protected $hierarchy_manager;

273 274 275 276 277 278 279 280
  /**
   * The facet source config object.
   *
   * @var \Drupal\Facets\FacetSourceInterface
   *   The facet source config object.
   */
  protected $facetSourceConfig;

281 282 283
  /**
   * The facet weight.
   *
284
   * @var int
285 286 287 288
   *   The weight of the facet.
   */
  protected $weight;

289 290 291
  /**
   * The minimum amount of results to show.
   *
292
   * @var int
293 294 295 296
   *   The minimum amount of results.
   */
  protected $min_count = 1;

297
  /**
298
   * Returns the widget plugin manager.
borisson_'s avatar
borisson_ committed
299
   *
300
   * @return \Drupal\facets\Widget\WidgetPluginManager
borisson_'s avatar
borisson_ committed
301
   *   The widget plugin manager.
302 303
   */
  public function getWidgetManager() {
304
    return $this->widget_plugin_manager ?: \Drupal::service('plugin.manager.facets.widget');
Nick_vh's avatar
Nick_vh committed
305 306
  }

307 308 309 310 311 312 313 314 315 316
  /**
   * Returns the hierarchy plugin manager.
   *
   * @return \Drupal\facets\Hierarchy\HierarchyPluginManager
   *   The hierarchy plugin manager.
   */
  public function getHierarchyManager() {
    return $this->hierarchy_manager ?: \Drupal::service('plugin.manager.facets.hierarchy');
  }

Nick_vh's avatar
Nick_vh committed
317 318 319 320 321 322 323
  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    return $this->description;
  }

324 325 326
  /**
   * {@inheritdoc}
   */
327 328 329 330 331 332 333 334 335 336
  public function setWidget($id, array $configuration = NULL) {
    if ($configuration === NULL) {
      $instance = $this->getWidgetManager()->createInstance($id);
      // Get the default configuration for this plugin.
      $configuration = $instance->getConfiguration();
    }
    $this->widget = ['type' => $id, 'config' => $configuration];

    // Unset the widget instance, if exists.
    unset($this->widgetInstance);
337 338
  }

borisson_'s avatar
borisson_ committed
339
  /**
340
   * {@inheritdoc}
borisson_'s avatar
borisson_ committed
341 342 343 344 345
   */
  public function getWidget() {
    return $this->widget;
  }

346 347 348 349
  /**
   * {@inheritdoc}
   */
  public function getWidgetInstance() {
350 351 352 353
    if ($this->widget === NULL) {
      throw new InvalidProcessorException();
    }

354 355 356 357 358 359 360 361
    if (!isset($this->widgetInstance)) {
      $definition = $this->getWidget();
      $this->widgetInstance = $this->getWidgetManager()
        ->createInstance($definition['type'], (array) $definition['config']);
    }
    return $this->widgetInstance;
  }

362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
  /**
   * {@inheritdoc}
   */
  public function setHierarchy($id, array $configuration = NULL) {
    if ($configuration === NULL) {
      $instance = $this->getHierarchyManager()->createInstance($id);
      // Get the default configuration for this plugin.
      $configuration = $instance->getConfiguration();
    }
    $this->hierarchy = ['type' => $id, 'config' => $configuration];

    // Unset the hierarchy instance, if exists.
    unset($this->hierarchy_instance);
  }

  /**
   * {@inheritdoc}
   */
  public function getHierarchy() {
    // TODO: do not hardcode on taxonomy, make this configurable (or better,
    // autoselected depending field type).
    return ['type' => 'taxonomy', 'config' => []];
384
    return $this->hierarchy;
385 386 387 388 389 390 391 392 393 394 395 396 397 398
  }

  /**
   * {@inheritdoc}
   */
  public function getHierarchyInstance() {
    if (!isset($this->hierarchy_instance)) {
      $definition = $this->getHierarchy();
      $this->hierarchy_instance = $this->getHierarchyManager()
        ->createInstance($definition['type'], (array) $definition['config']);
    }
    return $this->hierarchy_instance;
  }

399
  /**
400 401 402 403 404 405
   * Retrieves all processors supported by this facet.
   *
   * @return \Drupal\facets\Processor\ProcessorInterface[]
   *   The loaded processors, keyed by processor ID.
   */
  protected function loadProcessors() {
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    if (is_array($this->processors)) {
      return $this->processors;
    }

    /* @var $processor_plugin_manager \Drupal\facets\Processor\ProcessorPluginManager */
    $processor_plugin_manager = \Drupal::service('plugin.manager.facets.processor');
    $processor_settings = $this->getProcessorConfigs();

    foreach ($processor_plugin_manager->getDefinitions() as $name => $processor_definition) {
      if (class_exists($processor_definition['class']) && empty($this->processors[$name])) {
        // Create our settings for this processor.
        $settings = empty($processor_settings[$name]['settings']) ? [] : $processor_settings[$name]['settings'];
        $settings['facet'] = $this;

        /* @var $processor \Drupal\facets\Processor\ProcessorInterface */
        $processor = $processor_plugin_manager->createInstance($name, $settings);
        $this->processors[$name] = $processor;
      }
      elseif (!class_exists($processor_definition['class'])) {
        \Drupal::logger('facets')
426
          ->warning('Processor @id specifies a non-existing @class.', [
427 428
            '@id' => $name,
            '@class' => $processor_definition['class'],
429
          ]);
430 431 432 433
      }
    }

    return $this->processors;
434 435 436 437 438 439
  }

  /**
   * {@inheritdoc}
   */
  public function getProcessorConfigs() {
440
    return !empty($this->processor_configs) ? $this->processor_configs : [];
441 442 443
  }

  /**
444 445 446 447
   * {@inheritdoc}
   */
  public function getQueryType() {
    $facet_source = $this->getFacetSource();
448 449 450 451
    if (is_null($facet_source)) {
      throw new Exception("No facet source defined for facet.");
    }

452 453
    $query_types = $facet_source->getQueryTypesForFacet($this);

454
    // Get the widget configured for this facet.
455 456
    /** @var \Drupal\facets\Widget\WidgetPluginInterface $widget */
    $widget = $this->getWidgetInstance();
457

458
    // Give the widget the chance to select a preferred query type. This is
459 460
    // useful for widget that have different query type. See the date widget,
    // that needs to select the date query type.
461 462 463
    return $widget->getQueryType($query_types);
  }

464 465 466 467 468 469 470
  /**
   * {@inheritdoc}
   */
  public function setQueryOperator($operator = '') {
    return $this->query_operator = $operator;
  }

471 472 473 474
  /**
   * {@inheritdoc}
   */
  public function getQueryOperator() {
475
    return $this->query_operator ?: 'or';
476 477
  }

478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
  /**
   * {@inheritdoc}
   */
  public function setUseHierarchy($use_hierarchy) {
    return $this->use_hierarchy = $use_hierarchy;
  }

  /**
   * {@inheritdoc}
   */
  public function getUseHierarchy() {
    return $this->use_hierarchy;
  }

  /**
   * {@inheritdoc}
   */
  public function setExpandHierarchy($expand_hierarchy) {
    return $this->expand_hierarchy = $expand_hierarchy;
  }

  /**
   * {@inheritdoc}
   */
  public function getExpandHierarchy() {
    return $this->expand_hierarchy;
  }

  /**
   * {@inheritdoc}
   */
  public function setEnableParentWhenChildGetsDisabled($enable_parent_when_child_gets_disabled) {
    return $this->enable_parent_when_child_gets_disabled = $enable_parent_when_child_gets_disabled;
  }

  /**
   * {@inheritdoc}
   */
  public function getEnableParentWhenChildGetsDisabled() {
    return $this->enable_parent_when_child_gets_disabled;
  }

520 521 522 523 524 525 526 527 528 529 530 531 532 533
  /**
   * {@inheritdoc}
   */
  public function setHardLimit($limit) {
    return $this->hard_limit = $limit;
  }

  /**
   * {@inheritdoc}
   */
  public function getHardLimit() {
    return $this->hard_limit ?: 0;
  }

534 535 536 537 538 539 540 541 542 543 544 545 546 547
  /**
   * {@inheritdoc}
   */
  public function setExclude($exclude) {
    return $this->exclude = $exclude;
  }

  /**
   * {@inheritdoc}
   */
  public function getExclude() {
    return $this->exclude;
  }

Nick_vh's avatar
Nick_vh committed
548
  /**
borisson_'s avatar
borisson_ committed
549
   * {@inheritdoc}
Nick_vh's avatar
Nick_vh committed
550 551
   */
  public function getFieldAlias() {
552 553 554
    // For now, create the field alias based on the field identifier.
    $field_alias = preg_replace('/[:\/]+/', '_', $this->field_identifier);
    return $field_alias;
Nick_vh's avatar
Nick_vh committed
555 556 557
  }

  /**
borisson_'s avatar
borisson_ committed
558
   * {@inheritdoc}
Nick_vh's avatar
Nick_vh committed
559 560
   */
  public function setActiveItem($value) {
561 562 563
    if (!in_array($value, $this->active_values)) {
      $this->active_values[] = $value;
    }
Nick_vh's avatar
Nick_vh committed
564 565 566
  }

  /**
borisson_'s avatar
borisson_ committed
567
   * {@inheritdoc}
Nick_vh's avatar
Nick_vh committed
568 569
   */
  public function getActiveItems() {
Jur de Vries's avatar
Jur de Vries committed
570
    return $this->active_values;
Nick_vh's avatar
Nick_vh committed
571 572
  }

573 574 575 576 577 578 579
  /**
   * {@inheritdoc}
   */
  public function setActiveItems(array $values) {
    $this->active_values = $values;
  }

580
  /**
borisson_'s avatar
borisson_ committed
581
   * {@inheritdoc}
582
   */
583
  public function getFieldIdentifier() {
584
    return $this->field_identifier;
585 586
  }

587
  /**
borisson_'s avatar
borisson_ committed
588
   * {@inheritdoc}
589
   */
590 591
  public function setFieldIdentifier($field_identifier) {
    $this->field_identifier = $field_identifier;
592 593
  }

594
  /**
borisson_'s avatar
borisson_ committed
595
   * {@inheritdoc}
596
   */
597 598 599
  public function getName() {
    return $this->name;
  }
Nick_vh's avatar
Nick_vh committed
600

601 602 603 604 605 606 607 608 609 610 611 612 613 614
  /**
   * {@inheritdoc}
   */
  public function getUrlAlias() {
    return $this->url_alias;
  }

  /**
   * {@inheritdoc}
   */
  public function setUrlAlias($url_alias) {
    $this->url_alias = $url_alias;
  }

615 616 617
  /**
   * {@inheritdoc}
   */
618 619
  public function setFacetSourceId($facet_source_id) {
    $this->facet_source_id = $facet_source_id;
620 621 622 623 624 625 626
  }

  /**
   * {@inheritdoc}
   */
  public function getFacetSourceId() {
    return $this->facet_source_id;
627 628 629 630 631 632
  }

  /**
   * {@inheritdoc}
   */
  public function getFacetSource() {
633
    if (is_null($this->facet_source_instance) && $this->facet_source_id) {
borisson_'s avatar
borisson_ committed
634
      /* @var $facet_source_plugin_manager \Drupal\facets\FacetSource\FacetSourcePluginManager */
635
      $facet_source_plugin_manager = \Drupal::service('plugin.manager.facets.facet_source');
636
      if (!$facet_source_plugin_manager->hasDefinition($this->facet_source_id)) {
637
        return NULL;
638 639 640
      }
      $this->facet_source_instance = $facet_source_plugin_manager
        ->createInstance($this->facet_source_id, ['facet' => $this]);
641 642 643
    }

    return $this->facet_source_instance;
644 645
  }

646 647 648 649 650 651 652 653 654 655 656 657 658 659
  /**
   * {@inheritdoc}
   */
  public function getShowOnlyOneResult() {
    return $this->show_only_one_result;
  }

  /**
   * {@inheritdoc}
   */
  public function setShowOnlyOneResult($show_only_one_result) {
    $this->show_only_one_result = $show_only_one_result;
  }

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
  /**
   * {@inheritdoc}
   */
  public function getFacetSourceConfig() {
    // Return the facet source config object, if it's already set on the facet.
    if ($this->facetSourceConfig instanceof FacetSource) {
      return $this->facetSourceConfig;
    }

    $storage = \Drupal::entityTypeManager()->getStorage('facets_facet_source');
    $source_id = str_replace(':', '__', $this->facet_source_id);

    // Load and return the facet source config object from the storage.
    $facet_source = $storage->load($source_id);
    if ($facet_source instanceof FacetSource) {
      $this->facetSourceConfig = $facet_source;
      return $this->facetSourceConfig;
    }

    // We didn't have a facet source config entity yet for this facet source
    // plugin, so we create it on the fly.
    $facet_source = new FacetSource(
      [
        'id' => $source_id,
        'name' => $this->facet_source_id,
685 686
        'filter_key' => 'f',
        'url_processor' => 'query_string',
687 688 689 690
      ],
      'facets_facet_source'
    );

691
    return $facet_source;
692 693
  }

694
  /**
borisson_'s avatar
borisson_ committed
695
   * {@inheritdoc}
696
   */
Jur de Vries's avatar
Jur de Vries committed
697
  public function getResults() {
marthinal's avatar
marthinal committed
698
    return $this->results;
Jur de Vries's avatar
Jur de Vries committed
699 700
  }

borisson_'s avatar
borisson_ committed
701
  /**
borisson_'s avatar
borisson_ committed
702
   * {@inheritdoc}
borisson_'s avatar
borisson_ committed
703
   */
Jur de Vries's avatar
Jur de Vries committed
704 705
  public function setResults(array $results) {
    $this->results = $results;
706 707 708 709
    // If there are active values,
    // set the results which are active to active.
    if (count($this->active_values)) {
      foreach ($this->results as $result) {
710
        if (in_array($result->getRawValue(), $this->active_values)) {
711 712 713 714
          $result->setActiveState(TRUE);
        }
      }
    }
Jur de Vries's avatar
Jur de Vries committed
715
  }
716

717
  /**
borisson_'s avatar
borisson_ committed
718
   * {@inheritdoc}
719 720 721 722 723 724 725 726
   */
  public function isActiveValue($value) {
    $is_active = FALSE;
    if (in_array($value, $this->active_values)) {
      $is_active = TRUE;
    }
    return $is_active;
  }
727 728 729 730

  /**
   * {@inheritdoc}
   */
731
  public function getFacetSources($only_enabled = FALSE) {
732 733 734
    if (!isset($this->facetSourcePlugins)) {
      $this->facetSourcePlugins = [];

borisson_'s avatar
borisson_ committed
735
      /* @var $facet_source_plugin_manager \Drupal\facets\FacetSource\FacetSourcePluginManager */
736
      $facet_source_plugin_manager = \Drupal::service('plugin.manager.facets.facet_source');
737 738 739 740 741 742

      foreach ($facet_source_plugin_manager->getDefinitions() as $name => $facet_source_definition) {
        if (class_exists($facet_source_definition['class']) && empty($this->facetSourcePlugins[$name])) {
          // Create our settings for this facet source..
          $config = isset($this->facetSourcePlugins[$name]) ? $this->facetSourcePlugins[$name] : [];

743
          /* @var $facet_source \Drupal\facets\FacetSource\FacetSourcePluginInterface */
744 745 746 747
          $facet_source = $facet_source_plugin_manager->createInstance($name, $config);
          $this->facetSourcePlugins[$name] = $facet_source;
        }
        elseif (!class_exists($facet_source_definition['class'])) {
748 749 750
          \Drupal::logger('facets')
            ->warning('Facet Source @id specifies a non-existing @class.', [
              '@id' => $name,
751
              '@class' => $facet_source_definition['class'],
752
            ]);
753 754 755 756
        }
      }
    }

757
    // Filter facet sources by status if required.
758 759 760 761 762 763 764
    if (!$only_enabled) {
      return $this->facetSourcePlugins;
    }

    return array_intersect_key($this->facetSourcePlugins, array_flip($this->facetSourcePlugins));
  }

765 766 767 768 769 770 771
  /**
   * {@inheritdoc}
   */
  public function getProcessors($only_enabled = TRUE) {
    $processors = $this->loadProcessors();

    // Filter processors by status if required. Enabled processors are those
772
    // which have settings in the processor_configs.
773
    if ($only_enabled) {
774
      $processors_settings = $this->getProcessorConfigs();
775 776 777 778 779 780 781 782 783 784
      $processors = array_intersect_key($processors, $processors_settings);
    }

    return $processors;
  }

  /**
   * {@inheritdoc}
   */
  public function getProcessorsByStage($stage, $only_enabled = TRUE) {
785
    $processors = $this->getProcessors($only_enabled);
786
    $processor_settings = $this->getProcessorConfigs();
787
    $processor_weights = [];
788

789
    // Get a list of all processors for given stage.
790
    foreach ($processors as $name => $processor) {
791
      if ($processor->supportsStage($stage)) {
792 793 794 795 796 797 798 799 800 801 802 803
        if (!empty($processor_settings[$name]['weights'][$stage])) {
          $processor_weights[$name] = $processor_settings[$name]['weights'][$stage];
        }
        else {
          $processor_weights[$name] = $processor->getDefaultWeight($stage);
        }
      }
    }

    // Sort requested processors by weight.
    asort($processor_weights);

804
    $return_processors = [];
805 806 807 808 809 810
    foreach ($processor_weights as $name => $weight) {
      $return_processors[$name] = $processors[$name];
    }
    return $return_processors;
  }

811 812 813 814 815 816 817 818 819 820 821 822 823
  /**
   * {@inheritdoc}
   */
  public function setOnlyVisibleWhenFacetSourceIsVisible($only_visible_when_facet_source_is_visible) {
    $this->only_visible_when_facet_source_is_visible = $only_visible_when_facet_source_is_visible;
  }

  /**
   * {@inheritdoc}
   */
  public function getOnlyVisibleWhenFacetSourceIsVisible() {
    return $this->only_visible_when_facet_source_is_visible;
  }
824

825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
  /**
   * {@inheritdoc}
   */
  public function addProcessor(array $processor) {
    $this->processor_configs[$processor['processor_id']] = [
      'processor_id' => $processor['processor_id'],
      'weights' => $processor['weights'],
      'settings' => $processor['settings'],
    ];
    // Sort the processors so we won't have unnecessary changes.
    ksort($this->processor_configs);
  }

  /**
   * {@inheritdoc}
   */
  public function removeProcessor($processor_id) {
    unset($this->processor_configs[$processor_id]);
843
    unset($this->processors[$processor_id]);
844 845 846 847 848 849 850 851 852 853 854 855
  }

  /**
   * {@inheritdoc}
   */
  public function getEmptyBehavior() {
    return $this->empty_behavior;
  }

  /**
   * {@inheritdoc}
   */
856
  public function setEmptyBehavior(array $empty_behavior) {
857 858 859
    $this->empty_behavior = $empty_behavior;
  }

860 861 862 863 864 865 866 867 868 869 870 871 872 873
  /**
   * {@inheritdoc}
   */
  public function getWeight() {
    return $this->weight;
  }

  /**
   * {@inheritdoc}
   */
  public function setWeight($weight) {
    $this->weight = $weight;
  }

874 875 876 877 878 879 880 881 882 883 884 885 886 887
  /**
   * {@inheritdoc}
   */
  public function setMinCount($min_count) {
    $this->min_count = $min_count;
  }

  /**
   * {@inheritdoc}
   */
  public function getMinCount() {
    return $this->min_count;
  }

888 889 890 891 892
  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    parent::calculateDependencies();
893 894 895 896 897 898
    $source = $this->getFacetSource();
    if ($source === NULL) {
      return $this;
    }

    $facet_dependencies = $source->calculateDependencies();
899 900 901 902 903 904 905
    if (!empty($facet_dependencies)) {
      $this->addDependencies($facet_dependencies);
    }

    return $this;
  }

906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
  /**
   * {@inheritdoc}
   */
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    parent::postSave($storage, $update);
    if (!$update) {
      self::clearBlockCache();
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function postDelete(EntityStorageInterface $storage, array $entities) {
    parent::postDelete($storage, $entities);
    self::clearBlockCache();
  }

  /**
   * Clear the block cache.
   *
   * This includes resetting the shared plugin block manager as this can result
   * in the block definition cache being rebuilt in the same request with stale
   * static caches in the deriver.
   */
  protected static function clearBlockCache() {
    $container = \Drupal::getContainer();

    // If the block manager has already been loaded, we may have stale static
    // caches in the facet deriver, so lets clear it out.
    $container->set('plugin.manager.block', NULL);

    // Now rebuild the cache to force a fresh set of data.
    $container->get('plugin.manager.block')->clearCachedDefinitions();
  }

Nick_vh's avatar
Nick_vh committed
942
}