View source  
  <?php
namespace Drupal\Tests\search\Functional;
use Drupal\Core\Database\Database;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\search\SearchIndexInterface;
use Drupal\Tests\BrowserTestBase;
class SearchMultilingualEntityTest extends BrowserTestBase {
  
  protected $searchableNodes = [];
  
  protected $plugin;
  
  protected static $modules = [
    'language',
    'locale',
    'comment',
    'node',
    'search',
  ];
  
  protected $defaultTheme = 'stark';
  protected function setUp() : void {
    parent::setUp();
    $this
      ->drupalCreateContentType([
      'type' => 'page',
      'name' => 'Basic page',
    ]);
    
    $user = $this
      ->drupalCreateUser([
      'administer search',
      'search content',
      'use advanced search',
      'access content',
      'access site reports',
      'administer site configuration',
    ]);
    $this
      ->drupalLogin($user);
    
    $this->plugin = $this->container
      ->get('plugin.manager.search')
      ->createInstance('node_search');
    
    $this
      ->assertIndexCounts(0, 0, 'before adding nodes');
    $this
      ->assertDatabaseCounts(0, 0, 'before adding nodes');
    
    ConfigurableLanguage::createFromLangcode('hu')
      ->save();
    ConfigurableLanguage::createFromLangcode('sv')
      ->save();
    
    $field_storage = FieldStorageConfig::loadByName('node', 'body');
    $field_storage
      ->setTranslatable(TRUE);
    $field_storage
      ->save();
    
    $default_format = filter_default_format();
    $nodes = [
      [
        'title' => 'First node en',
        'type' => 'page',
        'body' => [
          [
            'value' => $this
              ->randomMachineName(32),
            'format' => $default_format,
          ],
        ],
        'langcode' => 'en',
      ],
      [
        'title' => 'Second node this is the English title',
        'type' => 'page',
        'body' => [
          [
            'value' => $this
              ->randomMachineName(32),
            'format' => $default_format,
          ],
        ],
        'langcode' => 'en',
      ],
      [
        'title' => 'Third node en',
        'type' => 'page',
        'body' => [
          [
            'value' => $this
              ->randomMachineName(32),
            'format' => $default_format,
          ],
        ],
        'langcode' => 'en',
      ],
      
      [],
      [],
      [],
      [],
      [],
    ];
    $this->searchableNodes = [];
    foreach ($nodes as $setting) {
      $this->searchableNodes[] = $this
        ->drupalCreateNode($setting);
    }
    
    $translation = $this->searchableNodes[1]
      ->addTranslation('hu', [
      'title' => 'Second node hu',
    ]);
    $translation->body->value = $this
      ->randomMachineName(32);
    $this->searchableNodes[1]
      ->save();
    
    $translation = $this->searchableNodes[2]
      ->addTranslation('hu', [
      'title' => 'Third node this is the Hungarian title',
    ]);
    $translation->body->value = $this
      ->randomMachineName(32);
    $translation = $this->searchableNodes[2]
      ->addTranslation('sv', [
      'title' => 'Third node sv',
    ]);
    $translation->body->value = $this
      ->randomMachineName(32);
    $this->searchableNodes[2]
      ->save();
    
    $this
      ->assertIndexCounts(8, 8, 'before updating the search index');
    $this
      ->assertDatabaseCounts(0, 0, 'before updating the search index');
  }
  
  public function testMultilingualSearch() {
    
    $this
      ->config('search.settings')
      ->set('index.cron_limit', 2)
      ->save();
    
    $this->plugin = $this->container
      ->get('plugin.manager.search')
      ->createInstance('node_search');
    
    $this->plugin
      ->updateIndex();
    
    $search_index = \Drupal::service('search.index');
    assert($search_index instanceof SearchIndexInterface);
    $this
      ->assertIndexCounts(6, 8, 'after updating partially');
    $this
      ->assertDatabaseCounts(2, 0, 'after updating partially');
    
    $this
      ->drupalGet('admin/config/search/pages');
    $this
      ->submitForm([
      'cron_limit' => 20,
    ], 'Save configuration');
    $this
      ->assertEquals(20, $this
      ->config('search.settings')
      ->get('index.cron_limit', 100), 'Config setting was saved correctly');
    
    $this->plugin = $this->container
      ->get('plugin.manager.search')
      ->createInstance('node_search');
    $this->plugin
      ->updateIndex();
    $this
      ->assertIndexCounts(0, 8, 'after updating fully');
    $this
      ->assertDatabaseCounts(8, 0, 'after updating fully');
    
    $this
      ->drupalGet('admin/config/search/pages');
    $this
      ->submitForm([], 'Re-index site');
    $this
      ->submitForm([], 'Re-index site');
    $this
      ->assertIndexCounts(8, 8, 'after reindex');
    $this
      ->assertDatabaseCounts(8, 0, 'after reindex');
    $this->plugin
      ->updateIndex();
    
    $this->plugin
      ->setSearch('English OR Hungarian', [], []);
    $search_result = $this->plugin
      ->execute();
    $this
      ->assertCount(2, $search_result, 'Found two results.');
    
    $results = [
      $search_result[0]['title'],
      $search_result[1]['title'],
    ];
    $this
      ->assertContains('Third node this is the Hungarian title', $results, 'The search finds the correct Hungarian title.');
    $this
      ->assertContains('Second node this is the English title', $results, 'The search finds the correct English title.');
    
    $this->plugin
      ->setSearch('English OR Hungarian', [
      'f' => [
        'language:hu',
      ],
    ], []);
    $search_result = $this->plugin
      ->execute();
    $this
      ->assertCount(1, $search_result, 'The search found only one result');
    $this
      ->assertEquals('Third node this is the Hungarian title', $search_result[0]['title'], 'The search finds the correct Hungarian title.');
    
    $this->plugin
      ->setSearch('node', [], []);
    $search_result = $this->plugin
      ->execute();
    $this
      ->assertCount(6, $search_result, 'The search found total six results');
    
    $this->plugin
      ->setSearch('node', [
      'f' => [
        'language:hu',
      ],
    ], []);
    $search_result = $this->plugin
      ->execute();
    $this
      ->assertCount(2, $search_result, 'The search found 2 results');
    
    foreach ($search_result as $result) {
      $this
        ->assertEquals('hu', $result['langcode'], 'The search found the correct Hungarian result');
    }
    
    $search_index
      ->markForReindex('node_search', $this->searchableNodes[0]
      ->id());
    $this
      ->assertIndexCounts(1, 8, 'after marking one node to reindex via API function');
    
    $this->plugin = $this->container
      ->get('plugin.manager.search')
      ->createInstance('node_search');
    $this->plugin
      ->updateIndex();
    $this
      ->assertIndexCounts(0, 8, 'after indexing again');
    
    $this->searchableNodes[1]
      ->save();
    $this
      ->assertIndexCounts(1, 8, 'after marking one node to reindex via save');
    
    $current = REQUEST_TIME;
    $old = $current - 10;
    $connection = Database::getConnection();
    $connection
      ->update('search_dataset')
      ->fields([
      'reindex' => $old,
    ])
      ->condition('reindex', $current, '>=')
      ->execute();
    
    $this->searchableNodes[1]
      ->save();
    $result = $connection
      ->select('search_dataset', 'd')
      ->fields('d', [
      'reindex',
    ])
      ->condition('type', 'node_search')
      ->condition('sid', $this->searchableNodes[1]
      ->id())
      ->execute()
      ->fetchField();
    $this
      ->assertEquals($old, $result, 'Reindex time was not updated if node was already marked');
    
    $search_index
      ->index('foo', $this->searchableNodes[0]
      ->id(), 'en', 'some text');
    $this
      ->assertIndexCounts(1, 8, 'after adding a different index item');
    
    $search_index
      ->markForReindex('foo');
    $this
      ->assertIndexCounts(1, 8, 'after reindexing the other search type');
    
    $search_index
      ->markForReindex();
    $this
      ->assertIndexCounts(8, 8, 'after reindexing everything');
    
    $this
      ->assertDatabaseCounts(8, 1, 'before clear');
    $search_index
      ->clear('node_search', $this->searchableNodes[0]
      ->id(), 'hu');
    $this
      ->assertDatabaseCounts(8, 1, 'after clear with wrong language');
    
    $search_index
      ->clear('node_search', $this->searchableNodes[0]
      ->id(), 'en');
    $this
      ->assertDatabaseCounts(7, 1, 'after clear with right language');
    
    $search_index
      ->clear('node_search', $this->searchableNodes[1]
      ->id());
    $this
      ->assertDatabaseCounts(6, 1, 'unspecified language clear');
    
    $search_index
      ->clear('foo');
    $this
      ->assertDatabaseCounts(6, 0, 'other index clear');
    
    $search_index
      ->clear();
    $this
      ->assertDatabaseCounts(0, 0, 'complete clear');
  }
  
  protected function assertIndexCounts($remaining, $total, $message) {
    
    $status = $this->plugin
      ->indexStatus();
    $this
      ->assertEquals($remaining, $status['remaining'], 'Remaining items ' . $message . ' is ' . $remaining);
    $this
      ->assertEquals($total, $status['total'], 'Total items ' . $message . ' is ' . $total);
    
    $indexed = $total - $remaining;
    $percent = $total > 0 ? floor(100 * $indexed / $total) : 100;
    $this
      ->drupalGet('admin/config/search/pages');
    $this
      ->assertSession()
      ->pageTextContains($percent . '% of the site has been indexed.');
    $this
      ->assertSession()
      ->pageTextContains($remaining . ' item');
    
    $this
      ->assertSession()
      ->pageTextContains($indexed . ' of ' . $total . ' indexed');
    
    $this
      ->drupalGet('admin/reports/status');
    $this
      ->assertSession()
      ->pageTextContains('Search index progress');
    $this
      ->assertSession()
      ->pageTextContains($percent . '%');
    $this
      ->assertSession()
      ->pageTextContains('(' . $remaining . ' remaining)');
  }
  
  protected function assertDatabaseCounts($count_node, $count_foo, $message) {
    
    $connection = Database::getConnection();
    $results = $connection
      ->select('search_dataset', 'i')
      ->fields('i', [
      'sid',
    ])
      ->condition('type', 'node_search')
      ->groupBy('sid')
      ->execute()
      ->fetchCol();
    $this
      ->assertCount($count_node, $results, 'Node count was ' . $count_node . ' for ' . $message);
    
    $results = $connection
      ->select('search_dataset', 'i')
      ->fields('i', [
      'sid',
    ])
      ->condition('type', 'foo')
      ->execute()
      ->fetchCol();
    $this
      ->assertCount($count_foo, $results, 'Foo count was ' . $count_foo . ' for ' . $message);
  }
}