<?php

namespace Drupal\Tests\visitors\Unit;

use Drupal\Tests\UnitTestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;

require_once __DIR__ . '/../../../visitors.module';

/**
 * Tests visitors_preprocess_html.
 *
 * @group visitors
 */
class HookPreprocessHtmlTest extends UnitTestCase {

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface|\PHPUnit\Framework\MockObject\MockObject
   */
  protected $configFactory;

  /**
   * The settings config.
   *
   * @var \Drupal\Core\Config\Config|\PHPUnit\Framework\MockObject\MockObject
   */
  protected $settings;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface|\PHPUnit\Framework\MockObject\MockObject
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();

    $container = new ContainerBuilder();

    $string_translation = $this->createMock('Drupal\Core\StringTranslation\TranslationInterface');
    $container->set('string_translation', $string_translation);

    \Drupal::setContainer($container);
  }

  /**
   * Tests visitors_preprocess_html().
   */
  public function testVisitorsPreprocessHtmlNoTitle() {
    $variables = [];

    visitors_preprocess_html($variables);

    $this->assertCount(0, $variables);
  }

  /**
   * Tests visitors_preprocess_html().
   */
  public function testVisitorsPreprocessHtmlMarkup() {
    $variables = [
      'head_title' => [
        'title' => 'Test title',
      ],
    ];

    visitors_preprocess_html($variables);

    $this->assertCount(2, $variables);
    $this->assertArrayHasKey('#attached', $variables);
    $this->assertArrayHasKey('drupalSettings', $variables['#attached']);
    $this->assertArrayHasKey('visitors', $variables['#attached']['drupalSettings']);
    $this->assertArrayHasKey('title', $variables['#attached']['drupalSettings']['visitors']);
    $this->assertEquals('Test title', $variables['#attached']['drupalSettings']['visitors']['title']);
  }

  /**
   * Tests visitors_preprocess_html().
   *
   * The html_head is a string.
   */
  public function testVisitorsPreprocessHtmlString() {
    $variables = [
      'head_title' => '<h1>Test title</h1>',
    ];

    visitors_preprocess_html($variables);

    $this->assertCount(2, $variables);
    $this->assertArrayHasKey('#attached', $variables);
    $this->assertArrayHasKey('drupalSettings', $variables['#attached']);
    $this->assertArrayHasKey('visitors', $variables['#attached']['drupalSettings']);
    $this->assertArrayHasKey('title', $variables['#attached']['drupalSettings']['visitors']);
    $this->assertEquals('Test title', $variables['#attached']['drupalSettings']['visitors']['title']);
  }

}
