You are here

public function AddHierarchyTest::testPreprocessIndexItems in Search API 8

Tests non-taxonomy-based hierarchy.

@covers ::preprocessIndexItems @covers ::addHierarchyValues

File

tests/src/Kernel/Processor/AddHierarchyTest.php, line 310

Class

AddHierarchyTest
Tests the "Hierarchy" processor.

Namespace

Drupal\Tests\search_api\Kernel\Processor

Code

public function testPreprocessIndexItems() {

  // Setup the nodes to follow the hierarchy.
  foreach (static::$hierarchy as $type => $items) {
    $this->nodes[] = $type_node = $this
      ->createNode([
      'title' => $type,
    ]);
    foreach ($items as $item) {
      $this->nodes[] = $this
        ->createNode([
        'title' => $item,
        'parent_reference' => [
          'target_id' => $type_node
            ->id(),
        ],
      ]);
    }
  }

  // Add a third tier of hierarchy for specific types of radishes.
  foreach ([
    'Cherry Belle',
    'Snow Belle',
    'Daikon',
  ] as $item) {
    $this->nodes[] = $this
      ->createNode([
      'title' => $item,
      'parent_reference' => [
        'target_id' => $this->nodes[5]
          ->id(),
      ],
    ]);
  }
  $this->index
    ->reindex();
  $this
    ->indexItems();

  // Initially hierarchy is excluded, so "vegetable" should only return nodes
  // 5 and 6.
  $query = new Query($this->index);
  $query
    ->addCondition('parent_reference', $this->nodes[3]
    ->id());
  $result = $query
    ->execute();
  $expected = [
    'node' => [
      4,
      5,
    ],
  ];
  $this
    ->assertResults($result, $expected);

  // Enable hierarchical indexing.
  $processor = $this->index
    ->getProcessor('hierarchy');
  $processor
    ->setConfiguration([
    'fields' => [
      'parent_reference' => 'node-parent_reference',
    ],
  ]);
  $this->index
    ->save();
  $this
    ->indexItems();

  // A search for "vegetable" should now include the hierarchy.
  $query = new Query($this->index);
  $query
    ->addCondition('parent_reference', $this->nodes[3]
    ->id());
  $result = $query
    ->execute();
  $expected = [
    'node' => [
      4,
      5,
      6,
      7,
      8,
    ],
  ];
  $this
    ->assertResults($result, $expected);
}