<?php

namespace Drupal\Tests\visitors\Unit;

use Drupal\Tests\UnitTestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\FormInterface;

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

/**
 * Tests visitors_form_alter.
 *
 * @group visitors
 */
class HookFormAlterTest extends UnitTestCase {

  /**
   * {@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_form_alter().
   */
  public function testVisitorsFormAlterNoBaseId() {
    $form = [];
    $form_state = $this->createMock(FormStateInterface::class);

    $form_object = $this->createMock(FormInterface::class);
    $form_object->method('getFormId')
      ->willReturn('test');

    $form_state->method('getFormObject')
      ->willReturn($form_object);

    $form_state->expects($this->once())
      ->method('getFormObject')
      ->willReturn($form_object);

    visitors_form_alter($form, $form_state, 'test');

    $this->assertArrayHasKey('#submit', $form);
    $this->assertContains('submit', $form['#submit'][0]);
    $this->assertContains('validate', $form['#validate'][0]);

    $static = &drupal_static('visitors_form_alter');
    $this->assertEquals('test', $static['test']);
  }

  /**
   * Tests visitors_form_alter().
   */
  public function testVisitorsFormAlterBaseId() {
    $form = [];
    $form_state = $this->createMock(FormStateInterface::class);

    $form_object = $this->createMock('\Drupal\Core\Entity\EntityForm');
    $form_object->method('getFormId')
      ->willReturn('node_article_form');

    $form_object->method('getBaseFormId')
      ->willReturn('node_form');
    $form_state->method('getFormObject')
      ->willReturn($form_object);

    $form_state->expects($this->once())
      ->method('getFormObject')
      ->willReturn($form_object);

    visitors_form_alter($form, $form_state, 'node_article_form');

    $this->assertArrayHasKey('#submit', $form);
    $this->assertContains('submit', $form['#submit'][0]);
    $this->assertContains('validate', $form['#validate'][0]);

    $static = &drupal_static('visitors_form_alter');
    $this->assertEquals('node_form', $static['node_article_form']);
  }

}
