PathValidatorTest.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace Drupal\KernelTests\Core\Path;
  3. use Drupal\Core\Routing\RequestContext;
  4. use Drupal\Core\Url;
  5. use Drupal\entity_test\Entity\EntityTest;
  6. use Drupal\KernelTests\KernelTestBase;
  7. use Drupal\Tests\user\Traits\UserCreationTrait;
  8. /**
  9. * Tests the path validator.
  10. *
  11. * @group Path
  12. *
  13. * @see \Drupal\Core\Path\PathValidator
  14. */
  15. class PathValidatorTest extends KernelTestBase {
  16. use UserCreationTrait;
  17. /**
  18. * {@inheritdoc}
  19. */
  20. public static $modules = ['path', 'entity_test', 'system', 'user'];
  21. /**
  22. * {@inheritdoc}
  23. */
  24. protected function setUp() {
  25. parent::setUp();
  26. $this->setUpCurrentUser();
  27. $this->installEntitySchema('entity_test');
  28. }
  29. public function testGetUrlIfValidWithoutAccessCheck() {
  30. $requestContext = \Drupal::service('router.request_context');
  31. $pathValidator = \Drupal::service('path.validator');
  32. $entity = EntityTest::create([
  33. 'name' => 'test',
  34. ]);
  35. $entity->save();
  36. $methods = [
  37. 'POST',
  38. 'GET',
  39. 'PUT',
  40. 'PATCH',
  41. 'DELETE',
  42. // Used in CLI context.
  43. NULL,
  44. // If no request was even pushed onto the request stack, and hence.
  45. FALSE,
  46. ];
  47. foreach ($methods as $method) {
  48. if ($method === FALSE) {
  49. $request_stack = $this->container->get('request_stack');
  50. while ($request_stack->getCurrentRequest()) {
  51. $request_stack->pop();
  52. }
  53. $this->container->set('router.request_context', new RequestContext());
  54. }
  55. $requestContext->setMethod($method);
  56. /** @var \Drupal\Core\Url $url */
  57. $url = $pathValidator->getUrlIfValidWithoutAccessCheck($entity->toUrl()->toString(TRUE)->getGeneratedUrl());
  58. $this->assertEquals($method, $requestContext->getMethod());
  59. $this->assertInstanceOf(Url::class, $url);
  60. $this->assertSame(['entity_test' => $entity->id()], $url->getRouteParameters());
  61. }
  62. }
  63. }