Newer
Older
Alex Pott
committed
<?php
/**
* @file
* Contains \Drupal\Tests\Core\Form\FormBuilderTest.
*/
namespace Drupal\Tests\Core\Form;
Alex Pott
committed
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultForbidden;
Alex Pott
committed
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\EnforcedResponseException;
use Drupal\Core\Form\FormBuilder;
use Drupal\Core\Form\FormBuilderInterface;
Alex Pott
committed
use Drupal\Core\Form\FormInterface;
Dries Buytaert
committed
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\AccountProxyInterface;
Alex Pott
committed
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
Alex Pott
committed
use Drupal\Core\Cache\Context\CacheContextsManager;
use Symfony\Component\DependencyInjection\ContainerBuilder;
Alex Pott
committed
/**
Angie Byron
committed
* @coversDefaultClass \Drupal\Core\Form\FormBuilder
Angie Byron
committed
* @group Form
Alex Pott
committed
*/
Angie Byron
committed
class FormBuilderTest extends FormTestBase {
Alex Pott
committed
Alex Pott
committed
/**
* The dependency injection container.
*
* @var \Symfony\Component\DependencyInjection\ContainerBuilder
*/
protected $container;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->container = new ContainerBuilder();
$cache_contexts_manager = $this->prophesize(CacheContextsManager::class)->reveal();
$this->container->set('cache_contexts_manager', $cache_contexts_manager);
\Drupal::setContainer($this->container);
}
Alex Pott
committed
/**
* Tests the getFormId() method with a string based form ID.
*
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The form argument foo is not a valid form.
Alex Pott
committed
*/
public function testGetFormIdWithString() {
$form_arg = 'foo';
Dries Buytaert
committed
$clean_form_state = new FormState();
$form_state = new FormState();
Alex Pott
committed
$form_id = $this->formBuilder->getFormId($form_arg, $form_state);
$this->assertSame($form_arg, $form_id);
Dries Buytaert
committed
$this->assertSame($clean_form_state, $form_state);
Alex Pott
committed
}
/**
* Tests the getFormId() method with a class name form ID.
*/
public function testGetFormIdWithClassName() {
$form_arg = 'Drupal\Tests\Core\Form\TestForm';
Dries Buytaert
committed
$form_state = new FormState();
Alex Pott
committed
$form_id = $this->formBuilder->getFormId($form_arg, $form_state);
$this->assertSame('test_form', $form_id);
$this->assertSame($form_arg, get_class($form_state->getFormObject()));
Alex Pott
committed
}
/**
* Tests the getFormId() method with an injected class name form ID.
*/
public function testGetFormIdWithInjectedClassName() {
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
\Drupal::setContainer($container);
$form_arg = 'Drupal\Tests\Core\Form\TestFormInjected';
Dries Buytaert
committed
$form_state = new FormState();
Alex Pott
committed
$form_id = $this->formBuilder->getFormId($form_arg, $form_state);
$this->assertSame('test_form', $form_id);
$this->assertSame($form_arg, get_class($form_state->getFormObject()));
Alex Pott
committed
}
/**
* Tests the getFormId() method with a form object.
*/
public function testGetFormIdWithObject() {
$expected_form_id = 'my_module_form_id';
Angie Byron
committed
$form_arg = $this->getMockForm($expected_form_id);
Alex Pott
committed
Dries Buytaert
committed
$form_state = new FormState();
Alex Pott
committed
$form_id = $this->formBuilder->getFormId($form_arg, $form_state);
$this->assertSame($expected_form_id, $form_id);
$this->assertSame($form_arg, $form_state->getFormObject());
Alex Pott
committed
}
/**
* Tests the getFormId() method with a base form object.
*/
public function testGetFormIdWithBaseForm() {
$expected_form_id = 'my_module_form_id';
$base_form_id = 'my_module';
$form_arg = $this->getMock('Drupal\Core\Form\BaseFormIdInterface');
$form_arg->expects($this->once())
->method('getFormId')
->will($this->returnValue($expected_form_id));
$form_arg->expects($this->once())
->method('getBaseFormId')
->will($this->returnValue($base_form_id));
Dries Buytaert
committed
$form_state = new FormState();
Alex Pott
committed
$form_id = $this->formBuilder->getFormId($form_arg, $form_state);
$this->assertSame($expected_form_id, $form_id);
$this->assertSame($form_arg, $form_state->getFormObject());
$this->assertSame($base_form_id, $form_state->getBuildInfo()['base_form_id']);
Alex Pott
committed
}
Alex Pott
committed
/**
* Tests the handling of FormStateInterface::$response.
Alex Pott
committed
*
* @dataProvider formStateResponseProvider
*/
public function testHandleFormStateResponse($class, $form_state_key) {
$form_id = 'test_form_id';
$expected_form = $form_id();
$response = $this->getMockBuilder($class)
->disableOriginalConstructor()
->getMock();
$form_arg = $this->getMockForm($form_id, $expected_form);
$form_arg->expects($this->any())
->method('submitForm')
Dries Buytaert
committed
->will($this->returnCallback(function ($form, FormStateInterface $form_state) use ($response, $form_state_key) {
$form_state->setFormState([$form_state_key => $response]);
Alex Pott
committed
}));
Dries Buytaert
committed
$form_state = new FormState();
Alex Pott
committed
try {
Angie Byron
committed
$input['form_id'] = $form_id;
$form_state->setUserInput($input);
Alex Pott
committed
$this->simulateFormSubmission($form_id, $form_arg, $form_state, FALSE);
$this->fail('EnforcedResponseException was not thrown.');
Alex Pott
committed
}
catch (EnforcedResponseException $e) {
$this->assertSame($response, $e->getResponse());
Alex Pott
committed
}
$this->assertSame($response, $form_state->getResponse());
Alex Pott
committed
}
/**
* Provides test data for testHandleFormStateResponse().
*/
public function formStateResponseProvider() {
return array(
array('Symfony\Component\HttpFoundation\Response', 'response'),
array('Symfony\Component\HttpFoundation\RedirectResponse', 'redirect'),
);
}
/**
* Tests the handling of a redirect when FormStateInterface::$response exists.
Alex Pott
committed
*/
public function testHandleRedirectWithResponse() {
$form_id = 'test_form_id';
$expected_form = $form_id();
// Set up a response that will be used.
$response = $this->getMockBuilder('Symfony\Component\HttpFoundation\Response')
->disableOriginalConstructor()
->getMock();
// Set up a redirect that will not be called.
$redirect = $this->getMockBuilder('Symfony\Component\HttpFoundation\RedirectResponse')
->disableOriginalConstructor()
->getMock();
$form_arg = $this->getMockForm($form_id, $expected_form);
$form_arg->expects($this->any())
->method('submitForm')
Dries Buytaert
committed
->will($this->returnCallback(function ($form, FormStateInterface $form_state) use ($response, $redirect) {
Alex Pott
committed
// Set both the response and the redirect.
$form_state->setResponse($response);
$form_state->set('redirect', $redirect);
Alex Pott
committed
}));
Dries Buytaert
committed
$form_state = new FormState();
Alex Pott
committed
try {
Angie Byron
committed
$input['form_id'] = $form_id;
$form_state->setUserInput($input);
Alex Pott
committed
$this->simulateFormSubmission($form_id, $form_arg, $form_state, FALSE);
$this->fail('EnforcedResponseException was not thrown.');
Alex Pott
committed
}
catch (EnforcedResponseException $e) {
$this->assertSame($response, $e->getResponse());
Alex Pott
committed
}
$this->assertSame($response, $form_state->getResponse());
Alex Pott
committed
}
Alex Pott
committed
/**
* Tests the getForm() method with a string based form ID.
*
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The form argument test_form_id is not a valid form.
Alex Pott
committed
*/
public function testGetFormWithString() {
$form_id = 'test_form_id';
$expected_form = $form_id();
$form = $this->formBuilder->getForm($form_id);
$this->assertFormElement($expected_form, $form, 'test');
$this->assertSame('test-form-id', $form['#id']);
Alex Pott
committed
}
/**
* Tests the getForm() method with a form object.
*/
public function testGetFormWithObject() {
$form_id = 'test_form_id';
$expected_form = $form_id();
Angie Byron
committed
$form_arg = $this->getMockForm($form_id, $expected_form);
Alex Pott
committed
$form = $this->formBuilder->getForm($form_arg);
$this->assertFormElement($expected_form, $form, 'test');
$this->assertArrayHasKey('#id', $form);
Alex Pott
committed
}
/**
Angie Byron
committed
* Tests the getForm() method with a class name based form ID.
Alex Pott
committed
*/
Angie Byron
committed
public function testGetFormWithClassString() {
$form_id = '\Drupal\Tests\Core\Form\TestForm';
$object = new TestForm();
$form = array();
Dries Buytaert
committed
$form_state = new FormState();
Angie Byron
committed
$expected_form = $object->buildForm($form, $form_state);
$form = $this->formBuilder->getForm($form_id);
$this->assertFormElement($expected_form, $form, 'test');
$this->assertSame('test-form', $form['#id']);
Angie Byron
committed
}
/**
* Tests the buildForm() method with a string based form ID.
*
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The form argument test_form_id is not a valid form.
Angie Byron
committed
*/
public function testBuildFormWithString() {
Alex Pott
committed
$form_id = 'test_form_id';
$expected_form = $form_id();
Angie Byron
committed
$form = $this->formBuilder->getForm($form_id);
$this->assertFormElement($expected_form, $form, 'test');
$this->assertArrayHasKey('#id', $form);
Angie Byron
committed
}
Alex Pott
committed
Angie Byron
committed
/**
* Tests the buildForm() method with a class name based form ID.
*/
public function testBuildFormWithClassString() {
$form_id = '\Drupal\Tests\Core\Form\TestForm';
$object = new TestForm();
$form = array();
Dries Buytaert
committed
$form_state = new FormState();
Angie Byron
committed
$expected_form = $object->buildForm($form, $form_state);
Alex Pott
committed
$form = $this->formBuilder->buildForm($form_id, $form_state);
$this->assertFormElement($expected_form, $form, 'test');
$this->assertSame('test-form', $form['#id']);
Angie Byron
committed
}
/**
* Tests the buildForm() method with a form object.
*/
public function testBuildFormWithObject() {
$form_id = 'test_form_id';
$expected_form = $form_id();
$form_arg = $this->getMockForm($form_id, $expected_form);
Dries Buytaert
committed
$form_state = new FormState();
Angie Byron
committed
$form = $this->formBuilder->buildForm($form_arg, $form_state);
$this->assertFormElement($expected_form, $form, 'test');
$this->assertSame($form_id, $form_state->getBuildInfo()['form_id']);
$this->assertArrayHasKey('#id', $form);
Alex Pott
committed
}
/**
* Tests the rebuildForm() method for a POST submission.
Alex Pott
committed
*/
public function testRebuildForm() {
$form_id = 'test_form_id';
$expected_form = $form_id();
Angie Byron
committed
// The form will be built four times.
Angie Byron
committed
$form_arg = $this->getMock('Drupal\Core\Form\FormInterface');
$form_arg->expects($this->exactly(2))
->method('getFormId')
->will($this->returnValue($form_id));
$form_arg->expects($this->exactly(4))
->method('buildForm')
->will($this->returnValue($expected_form));
Alex Pott
committed
// Do an initial build of the form and track the build ID.
Dries Buytaert
committed
$form_state = new FormState();
Angie Byron
committed
$form = $this->formBuilder->buildForm($form_arg, $form_state);
Alex Pott
committed
$original_build_id = $form['#build_id'];
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
$this->request->setMethod('POST');
$form_state->setRequestMethod('POST');
// Rebuild the form, and assert that the build ID has not changed.
$form_state->setRebuild();
$input['form_id'] = $form_id;
$form_state->setUserInput($input);
$form_state->addRebuildInfo('copy', ['#build_id' => TRUE]);
$this->formBuilder->processForm($form_id, $form, $form_state);
$this->assertSame($original_build_id, $form['#build_id']);
$this->assertTrue($form_state->isCached());
// Rebuild the form again, and assert that there is a new build ID.
$form_state->setRebuildInfo([]);
$form = $this->formBuilder->buildForm($form_arg, $form_state);
$this->assertNotSame($original_build_id, $form['#build_id']);
$this->assertTrue($form_state->isCached());
}
/**
* Tests the rebuildForm() method for a GET submission.
*/
public function testRebuildFormOnGetRequest() {
$form_id = 'test_form_id';
$expected_form = $form_id();
// The form will be built four times.
$form_arg = $this->getMock('Drupal\Core\Form\FormInterface');
$form_arg->expects($this->exactly(2))
->method('getFormId')
->will($this->returnValue($form_id));
$form_arg->expects($this->exactly(4))
->method('buildForm')
->will($this->returnValue($expected_form));
// Do an initial build of the form and track the build ID.
$form_state = new FormState();
$form_state->setMethod('GET');
$form = $this->formBuilder->buildForm($form_arg, $form_state);
$original_build_id = $form['#build_id'];
Alex Pott
committed
// Rebuild the form, and assert that the build ID has not changed.
$form_state->setRebuild();
Angie Byron
committed
$input['form_id'] = $form_id;
$form_state->setUserInput($input);
$form_state->addRebuildInfo('copy', ['#build_id' => TRUE]);
Alex Pott
committed
$this->formBuilder->processForm($form_id, $form, $form_state);
$this->assertSame($original_build_id, $form['#build_id']);
$this->assertFalse($form_state->isCached());
Alex Pott
committed
// Rebuild the form again, and assert that there is a new build ID.
$form_state->setRebuildInfo([]);
Angie Byron
committed
$form = $this->formBuilder->buildForm($form_arg, $form_state);
Alex Pott
committed
$this->assertNotSame($original_build_id, $form['#build_id']);
$this->assertFalse($form_state->isCached());
Alex Pott
committed
}
/**
* Tests the getCache() method.
*/
public function testGetCache() {
$form_id = 'test_form_id';
$expected_form = $form_id();
Angie Byron
committed
$expected_form['#token'] = FALSE;
Alex Pott
committed
Angie Byron
committed
// FormBuilder::buildForm() will be called twice, but the form object will
// only be called once due to caching.
$form_arg = $this->getMock('Drupal\Core\Form\FormInterface');
$form_arg->expects($this->exactly(2))
->method('getFormId')
->will($this->returnValue($form_id));
$form_arg->expects($this->once())
->method('buildForm')
->will($this->returnValue($expected_form));
Alex Pott
committed
// Do an initial build of the form and track the build ID.
$form_state = (new FormState())
->addBuildInfo('files', [['module' => 'node', 'type' => 'pages.inc']])
->setRequestMethod('POST')
->setCached();
Angie Byron
committed
$form = $this->formBuilder->buildForm($form_arg, $form_state);
Alex Pott
committed
$cached_form = $form;
$cached_form['#cache_token'] = 'csrf_token';
// The form cache, form_state cache, and CSRF token validation will only be
// called on the cached form.
Angie Byron
committed
$this->formCache->expects($this->once())
Angie Byron
committed
->method('getCache')
->willReturn($form);
Alex Pott
committed
// The final form build will not trigger any actual form building, but will
// use the form cache.
$form_state->setExecuted();
Angie Byron
committed
$input['form_id'] = $form_id;
$input['form_build_id'] = $form['#build_id'];
$form_state->setUserInput($input);
$this->formBuilder->buildForm($form_arg, $form_state);
$this->assertEmpty($form_state->getErrors());
Alex Pott
committed
}
Alex Pott
committed
/**
* Tests that HTML IDs are unique when rebuilding a form with errors.
*/
public function testUniqueHtmlId() {
$form_id = 'test_form_id';
$expected_form = $form_id();
$expected_form['test']['#required'] = TRUE;
// Mock a form object that will be built two times.
$form_arg = $this->getMock('Drupal\Core\Form\FormInterface');
$form_arg->expects($this->exactly(2))
->method('getFormId')
->will($this->returnValue($form_id));
Alex Pott
committed
$form_arg->expects($this->exactly(2))
->method('buildForm')
->will($this->returnValue($expected_form));
$form_state = new FormState();
Alex Pott
committed
$form = $this->simulateFormSubmission($form_id, $form_arg, $form_state);
$this->assertSame('test-form-id', $form['#id']);
Alex Pott
committed
$form_state = new FormState();
Alex Pott
committed
$form = $this->simulateFormSubmission($form_id, $form_arg, $form_state);
$this->assertSame('test-form-id--2', $form['#id']);
Alex Pott
committed
}
/**
* Tests that a cached form is deleted after submit.
*/
public function testFormCacheDeletionCached() {
$form_id = 'test_form_id';
$form_build_id = $this->randomMachineName();
$expected_form = $form_id();
$expected_form['#build_id'] = $form_build_id;
$form_arg = $this->getMockForm($form_id, $expected_form);
$form_arg->expects($this->once())
->method('submitForm')
->willReturnCallback(function (array &$form, FormStateInterface $form_state) {
// Mimic EntityForm by cleaning the $form_state upon submit.
$form_state->cleanValues();
});
$this->formCache->expects($this->once())
->method('deleteCache')
->with($form_build_id);
$form_state = new FormState();
$form_state->setRequestMethod('POST');
$form_state->setCached();
$this->simulateFormSubmission($form_id, $form_arg, $form_state);
}
/**
* Tests that an uncached form does not trigger cache set or delete.
*/
public function testFormCacheDeletionUncached() {
$form_id = 'test_form_id';
$form_build_id = $this->randomMachineName();
$expected_form = $form_id();
$expected_form['#build_id'] = $form_build_id;
$form_arg = $this->getMockForm($form_id, $expected_form);
$this->formCache->expects($this->never())
->method('deleteCache');
$form_state = new FormState();
$this->simulateFormSubmission($form_id, $form_arg, $form_state);
}
/**
* @covers ::buildForm
*
* @expectedException \Drupal\Core\Form\Exception\BrokenPostRequestException
*/
public function testExceededFileSize() {
$request = new Request([FormBuilderInterface::AJAX_FORM_REQUEST => TRUE]);
$request_stack = new RequestStack();
$request_stack->push($request);
$this->formBuilder = $this->getMockBuilder('\Drupal\Core\Form\FormBuilder')
->setConstructorArgs([$this->formValidator, $this->formSubmitter, $this->formCache, $this->moduleHandler, $this->eventDispatcher, $request_stack, $this->classResolver, $this->elementInfo, $this->themeManager, $this->csrfToken])
->setMethods(['getFileUploadMaxSize'])
->getMock();
$this->formBuilder->expects($this->once())
->method('getFileUploadMaxSize')
->willReturn(33554432);
$form_arg = $this->getMockForm('test_form_id');
$form_state = new FormState();
$this->formBuilder->buildForm($form_arg, $form_state);
}
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
/**
* @covers ::buildForm
*
* @dataProvider providerTestChildAccessInheritance
*/
public function testChildAccessInheritance($element, $access_checks) {
$form_arg = new TestFormWithPredefinedForm();
$form_arg->setForm($element);
$form_state = new FormState();
$form = $this->formBuilder->buildForm($form_arg, $form_state);
$actual_access_structure = [];
$expected_access_structure = [];
// Ensure that the expected access checks are set.
foreach ($access_checks as $access_check) {
$parents = $access_check[0];
$parents[] = '#access';
$actual_access = NestedArray::getValue($form, $parents);
$actual_access_structure[] = [$parents, $actual_access];
$expected_access_structure[] = [$parents, $access_check[1]];
}
$this->assertEquals($expected_access_structure, $actual_access_structure);
}
/**
* Data provider for testChildAccessInheritance.
*
* @return array
*/
public function providerTestChildAccessInheritance() {
$data = [];
$element = [
'child0' => [
'#type' => 'checkbox',
],
'child1' => [
'#type' => 'checkbox',
],
'child2' => [
'#type' => 'fieldset',
'child2.0' => [
'#type' => 'checkbox',
],
'child2.1' => [
'#type' => 'checkbox',
],
'child2.2' => [
'#type' => 'checkbox',
],
],
];
// Sets access FALSE on the root level, this should be inherited completely.
$clone = $element;
$clone['#access'] = FALSE;
$expected_access = [];
$expected_access[] = [[], FALSE];
$expected_access[] = [['child0'], FALSE];
$expected_access[] = [['child1'], FALSE];
$expected_access[] = [['child2'], FALSE];
$expected_access[] = [['child2', 'child2.0'], FALSE];
$expected_access[] = [['child2', 'child2.1'], FALSE];
$expected_access[] = [['child2', 'child2.2'], FALSE];
$data['access-false-root'] = [$clone, $expected_access];
$clone = $element;
Alex Pott
committed
$access_result = AccessResult::forbidden();
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
$clone['#access'] = $access_result;
$expected_access = [];
$expected_access[] = [[], $access_result];
$expected_access[] = [['child0'], $access_result];
$expected_access[] = [['child1'], $access_result];
$expected_access[] = [['child2'], $access_result];
$expected_access[] = [['child2', 'child2.0'], $access_result];
$expected_access[] = [['child2', 'child2.1'], $access_result];
$expected_access[] = [['child2', 'child2.2'], $access_result];
$data['access-forbidden-root'] = [$clone, $expected_access];
// Allow access on the most outer level but set FALSE otherwise.
$clone = $element;
$clone['#access'] = TRUE;
$clone['child0']['#access'] = FALSE;
$expected_access = [];
$expected_access[] = [[], TRUE];
$expected_access[] = [['child0'], FALSE];
$expected_access[] = [['child1'], NULL];
$expected_access[] = [['child2'], NULL];
$expected_access[] = [['child2', 'child2.0'], NULL];
$expected_access[] = [['child2', 'child2.1'], NULL];
$expected_access[] = [['child2', 'child2.2'], NULL];
$data['access-true-root'] = [$clone, $expected_access];
// Allow access on the most outer level but forbid otherwise.
$clone = $element;
Alex Pott
committed
$access_result_allowed = AccessResult::allowed();
$clone['#access'] = $access_result_allowed;
Alex Pott
committed
$access_result_forbidden = AccessResult::forbidden();
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
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
685
686
$clone['child0']['#access'] = $access_result_forbidden;
$expected_access = [];
$expected_access[] = [[], $access_result_allowed];
$expected_access[] = [['child0'], $access_result_forbidden];
$expected_access[] = [['child1'], NULL];
$expected_access[] = [['child2'], NULL];
$expected_access[] = [['child2', 'child2.0'], NULL];
$expected_access[] = [['child2', 'child2.1'], NULL];
$expected_access[] = [['child2', 'child2.2'], NULL];
$data['access-allowed-root'] = [$clone, $expected_access];
// Allow access on the most outer level, deny access on a parent, and allow
// on a child. The denying should be inherited.
$clone = $element;
$clone['#access'] = TRUE;
$clone['child2']['#access'] = FALSE;
$clone['child2.0']['#access'] = TRUE;
$clone['child2.1']['#access'] = TRUE;
$clone['child2.2']['#access'] = TRUE;
$expected_access = [];
$expected_access[] = [[], TRUE];
$expected_access[] = [['child0'], NULL];
$expected_access[] = [['child1'], NULL];
$expected_access[] = [['child2'], FALSE];
$expected_access[] = [['child2', 'child2.0'], FALSE];
$expected_access[] = [['child2', 'child2.1'], FALSE];
$expected_access[] = [['child2', 'child2.2'], FALSE];
$data['access-mixed-parents'] = [$clone, $expected_access];
$clone = $element;
$clone['#access'] = $access_result_allowed;
$clone['child2']['#access'] = $access_result_forbidden;
$clone['child2.0']['#access'] = $access_result_allowed;
$clone['child2.1']['#access'] = $access_result_allowed;
$clone['child2.2']['#access'] = $access_result_allowed;
$expected_access = [];
$expected_access[] = [[], $access_result_allowed];
$expected_access[] = [['child0'], NULL];
$expected_access[] = [['child1'], NULL];
$expected_access[] = [['child2'], $access_result_forbidden];
$expected_access[] = [['child2', 'child2.0'], $access_result_forbidden];
$expected_access[] = [['child2', 'child2.1'], $access_result_forbidden];
$expected_access[] = [['child2', 'child2.2'], $access_result_forbidden];
$data['access-mixed-parents-object'] = [$clone, $expected_access];
return $data;
}
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
/**
* @covers ::valueCallableIsSafe
*
* @dataProvider providerTestValueCallableIsSafe
*/
public function testValueCallableIsSafe($callback, $expected) {
$method = new \ReflectionMethod(FormBuilder::class, 'valueCallableIsSafe');
$method->setAccessible(true);
$is_safe = $method->invoke($this->formBuilder, $callback);
$this->assertSame($expected, $is_safe);
}
public function providerTestValueCallableIsSafe() {
$data = [];
$data['string_no_slash'] = [
'Drupal\Core\Render\Element\Token::valueCallback',
TRUE,
];
$data['string_with_slash'] = [
'\Drupal\Core\Render\Element\Token::valueCallback',
TRUE,
];
$data['array_no_slash'] = [
['Drupal\Core\Render\Element\Token', 'valueCallback'],
TRUE,
];
$data['array_with_slash'] = [
['\Drupal\Core\Render\Element\Token', 'valueCallback'],
TRUE,
];
$data['closure'] = [
function () {},
FALSE,
];
return $data;
}
/**
* @covers ::doBuildForm
*
* @dataProvider providerTestInvalidToken
*/
public function testInvalidToken($expected, $valid_token, $user_is_authenticated) {
$form_token = 'the_form_token';
$form_id = 'test_form_id';
if (is_bool($valid_token)) {
$this->csrfToken->expects($this->any())
->method('get')
->willReturnArgument(0);
$this->csrfToken->expects($this->atLeastOnce())
->method('validate')
->will($this->returnValueMap([
[$form_token, $form_id, $valid_token],
[$form_id, $form_id, $valid_token],
]));
}
$current_user = $this->prophesize(AccountInterface::class);
$current_user->isAuthenticated()->willReturn($user_is_authenticated);
$property = new \ReflectionProperty(FormBuilder::class, 'currentUser');
$property->setAccessible(TRUE);
$property->setValue($this->formBuilder, $current_user->reveal());
$expected_form = $form_id();
$form_arg = $this->getMockForm($form_id, $expected_form);
$form_state = new FormState();
$input['form_id'] = $form_id;
$input['form_token'] = $form_token;
$form_state->setUserInput($input);
$this->simulateFormSubmission($form_id, $form_arg, $form_state, FALSE);
$this->assertSame($expected, $form_state->hasInvalidToken());
}
public function providerTestInvalidToken() {
$data = [];
$data['authenticated_invalid'] = [TRUE, FALSE, TRUE];
$data['authenticated_valid'] = [FALSE, TRUE, TRUE];
// If the user is not authenticated, we will not have a token.
$data['anonymous'] = [FALSE, NULL, FALSE];
return $data;
}
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
/**
* @covers ::prepareForm
*
* @dataProvider providerTestFormTokenCacheability
*/
function testFormTokenCacheability($token, $is_authenticated, $expected_form_cacheability, $expected_token_cacheability) {
$user = $this->prophesize(AccountProxyInterface::class);
$user->isAuthenticated()
->willReturn($is_authenticated);
$this->container->set('current_user', $user->reveal());
\Drupal::setContainer($this->container);
$form_id = 'test_form_id';
$form = $form_id();
if (isset($token)) {
$form['#token'] = $token;
}
$form_arg = $this->getMock('Drupal\Core\Form\FormInterface');
$form_arg->expects($this->once())
->method('getFormId')
->will($this->returnValue($form_id));
$form_arg->expects($this->once())
->method('buildForm')
->will($this->returnValue($form));
$form_state = new FormState();
$built_form = $this->formBuilder->buildForm($form_arg, $form_state);
if (!isset($expected_form_cacheability)) {
$this->assertFalse(isset($built_form['#cache']));
}
else {
$this->assertTrue(isset($built_form['#cache']));
$this->assertEquals($expected_form_cacheability, $built_form['#cache']);
}
if (!isset($expected_token_cacheability)) {
$this->assertFalse(isset($built_form['form_token']));
}
else {
$this->assertTrue(isset($built_form['form_token']));
$this->assertEquals($expected_token_cacheability, $built_form['form_token']['#cache']);
}
}
/**
* Data provider for testFormTokenCacheability.
*
* @return array
*/
function providerTestFormTokenCacheability() {
return [
'token:none,authenticated:true' => [NULL, TRUE, ['contexts' => ['user.roles:authenticated']], ['max-age' => 0]],
'token:false,authenticated:true' => [FALSE, TRUE, NULL, NULL],
'token:none,authenticated:false' => [NULL, FALSE, ['contexts' => ['user.roles:authenticated']], NULL],
'token:false,authenticated:false' => [FALSE, FALSE, NULL, NULL],
];
}
Alex Pott
committed
}
class TestForm implements FormInterface {
public function getFormId() {
return 'test_form';
}
Dries Buytaert
committed
public function buildForm(array $form, FormStateInterface $form_state) {
Angie Byron
committed
return test_form_id();
}
Dries Buytaert
committed
public function validateForm(array &$form, FormStateInterface $form_state) { }
public function submitForm(array &$form, FormStateInterface $form_state) { }
Alex Pott
committed
}
class TestFormInjected extends TestForm implements ContainerInjectionInterface {
public static function create(ContainerInterface $container) {
return new static();
}
}
class TestFormWithPredefinedForm extends TestForm {
/**
* @var array
*/
protected $form;
public function setForm($form) {
$this->form = $form;
}
public function buildForm(array $form, FormStateInterface $form_state) {
return $this->form;
}
}