annotate core/tests/Drupal/Tests/Core/UrlTest.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents 4c8ae668cc8c
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /**
Chris@0 4 * @file
Chris@0 5 * Contains \Drupal\Tests\Core\UrlTest.
Chris@0 6 */
Chris@0 7
Chris@0 8 namespace Drupal\Tests\Core;
Chris@0 9
Chris@0 10 use Drupal\Component\Utility\UrlHelper;
Chris@0 11 use Drupal\Core\Access\AccessManagerInterface;
Chris@0 12 use Drupal\Core\DependencyInjection\ContainerBuilder;
Chris@0 13 use Drupal\Core\GeneratedUrl;
Chris@0 14 use Drupal\Core\Routing\RouteMatch;
Chris@0 15 use Drupal\Core\Url;
Chris@0 16 use Drupal\Tests\UnitTestCase;
Chris@0 17 use Symfony\Cmf\Component\Routing\RouteObjectInterface;
Chris@0 18 use Symfony\Component\HttpFoundation\ParameterBag;
Chris@0 19 use Symfony\Component\HttpFoundation\Request;
Chris@0 20 use Symfony\Component\Routing\Exception\InvalidParameterException;
Chris@0 21 use Symfony\Component\Routing\Exception\ResourceNotFoundException;
Chris@0 22 use Symfony\Component\Routing\Route;
Chris@0 23
Chris@0 24 /**
Chris@0 25 * @coversDefaultClass \Drupal\Core\Url
Chris@0 26 * @group UrlTest
Chris@0 27 */
Chris@0 28 class UrlTest extends UnitTestCase {
Chris@0 29
Chris@0 30 /**
Chris@0 31 * @var \Symfony\Component\DependencyInjection\ContainerInterface
Chris@0 32 */
Chris@0 33 protected $container;
Chris@0 34
Chris@0 35 /**
Chris@0 36 * The URL generator
Chris@0 37 *
Chris@0 38 * @var \Drupal\Core\Routing\UrlGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
Chris@0 39 */
Chris@0 40 protected $urlGenerator;
Chris@0 41
Chris@0 42 /**
Chris@0 43 * The path alias manager.
Chris@0 44 *
Chris@0 45 * @var \Drupal\Core\Path\AliasManagerInterface|\PHPUnit_Framework_MockObject_MockObject
Chris@0 46 */
Chris@0 47 protected $pathAliasManager;
Chris@0 48
Chris@0 49 /**
Chris@0 50 * The router.
Chris@0 51 *
Chris@0 52 * @var \Drupal\Tests\Core\Routing\TestRouterInterface|\PHPUnit_Framework_MockObject_MockObject
Chris@0 53 */
Chris@0 54 protected $router;
Chris@0 55
Chris@0 56 /**
Chris@0 57 * An array of values to use for the test.
Chris@0 58 *
Chris@0 59 * @var array
Chris@0 60 */
Chris@0 61 protected $map;
Chris@0 62
Chris@0 63 /**
Chris@0 64 * The mocked path validator.
Chris@0 65 *
Chris@0 66 * @var \Drupal\Core\Path\PathValidatorInterface|\PHPUnit_Framework_MockObject_MockObject
Chris@0 67 */
Chris@0 68 protected $pathValidator;
Chris@0 69
Chris@0 70 /**
Chris@0 71 * {@inheritdoc}
Chris@0 72 */
Chris@0 73 protected function setUp() {
Chris@0 74 parent::setUp();
Chris@0 75
Chris@0 76 $map = [];
Chris@0 77 $map[] = ['view.frontpage.page_1', [], [], FALSE, '/node'];
Chris@0 78 $map[] = ['node_view', ['node' => '1'], [], FALSE, '/node/1'];
Chris@0 79 $map[] = ['node_edit', ['node' => '2'], [], FALSE, '/node/2/edit'];
Chris@0 80 $this->map = $map;
Chris@0 81
Chris@0 82 $alias_map = [
Chris@0 83 // Set up one proper alias that can be resolved to a system path.
Chris@0 84 ['node-alias-test', NULL, FALSE, 'node'],
Chris@0 85 // Passing in anything else should return the same string.
Chris@0 86 ['node', NULL, FALSE, 'node'],
Chris@0 87 ['node/1', NULL, FALSE, 'node/1'],
Chris@0 88 ['node/2/edit', NULL, FALSE, 'node/2/edit'],
Chris@0 89 ['non-existent', NULL, FALSE, 'non-existent'],
Chris@0 90 ];
Chris@0 91
Chris@0 92 // $this->map has $collect_bubbleable_metadata = FALSE; also generate the
Chris@0 93 // $collect_bubbleable_metadata = TRUE case for ::generateFromRoute().
Chris@0 94 $generate_from_route_map = [];
Chris@0 95 foreach ($this->map as $values) {
Chris@0 96 $generate_from_route_map[] = $values;
Chris@0 97 $generate_from_route_map[] = [$values[0], $values[1], $values[2], TRUE, (new GeneratedUrl())->setGeneratedUrl($values[4])];
Chris@0 98 }
Chris@0 99 $this->urlGenerator = $this->getMock('Drupal\Core\Routing\UrlGeneratorInterface');
Chris@0 100 $this->urlGenerator->expects($this->any())
Chris@0 101 ->method('generateFromRoute')
Chris@0 102 ->will($this->returnValueMap($generate_from_route_map));
Chris@0 103
Chris@0 104 $this->pathAliasManager = $this->getMock('Drupal\Core\Path\AliasManagerInterface');
Chris@0 105 $this->pathAliasManager->expects($this->any())
Chris@0 106 ->method('getPathByAlias')
Chris@0 107 ->will($this->returnValueMap($alias_map));
Chris@0 108
Chris@0 109 $this->router = $this->getMock('Drupal\Tests\Core\Routing\TestRouterInterface');
Chris@0 110 $this->pathValidator = $this->getMock('Drupal\Core\Path\PathValidatorInterface');
Chris@0 111
Chris@0 112 $this->container = new ContainerBuilder();
Chris@0 113 $this->container->set('router.no_access_checks', $this->router);
Chris@0 114 $this->container->set('url_generator', $this->urlGenerator);
Chris@0 115 $this->container->set('path.alias_manager', $this->pathAliasManager);
Chris@0 116 $this->container->set('path.validator', $this->pathValidator);
Chris@0 117 \Drupal::setContainer($this->container);
Chris@0 118 }
Chris@0 119
Chris@0 120 /**
Chris@0 121 * Tests creating a Url from a request.
Chris@0 122 */
Chris@0 123 public function testUrlFromRequest() {
Chris@0 124 $this->router->expects($this->at(0))
Chris@0 125 ->method('matchRequest')
Chris@0 126 ->with($this->getRequestConstraint('/node'))
Chris@0 127 ->willReturn([
Chris@0 128 RouteObjectInterface::ROUTE_NAME => 'view.frontpage.page_1',
Chris@0 129 '_raw_variables' => new ParameterBag(),
Chris@0 130 ]);
Chris@0 131 $this->router->expects($this->at(1))
Chris@0 132 ->method('matchRequest')
Chris@0 133 ->with($this->getRequestConstraint('/node/1'))
Chris@0 134 ->willReturn([
Chris@0 135 RouteObjectInterface::ROUTE_NAME => 'node_view',
Chris@0 136 '_raw_variables' => new ParameterBag(['node' => '1']),
Chris@0 137 ]);
Chris@0 138 $this->router->expects($this->at(2))
Chris@0 139 ->method('matchRequest')
Chris@0 140 ->with($this->getRequestConstraint('/node/2/edit'))
Chris@0 141 ->willReturn([
Chris@0 142 RouteObjectInterface::ROUTE_NAME => 'node_edit',
Chris@0 143 '_raw_variables' => new ParameterBag(['node' => '2']),
Chris@0 144 ]);
Chris@0 145
Chris@0 146 $urls = [];
Chris@0 147 foreach ($this->map as $index => $values) {
Chris@0 148 $path = array_pop($values);
Chris@0 149 $url = Url::createFromRequest(Request::create("$path"));
Chris@0 150 $expected = Url::fromRoute($values[0], $values[1], $values[2]);
Chris@0 151 $this->assertEquals($expected, $url);
Chris@0 152 $urls[$index] = $url;
Chris@0 153 }
Chris@0 154 return $urls;
Chris@0 155 }
Chris@0 156
Chris@0 157 /**
Chris@0 158 * This constraint checks whether a Request object has the right path.
Chris@0 159 *
Chris@0 160 * @param string $path
Chris@0 161 * The path.
Chris@0 162 *
Chris@0 163 * @return \PHPUnit_Framework_Constraint_Callback
Chris@0 164 * The constraint checks whether a Request object has the right path.
Chris@0 165 */
Chris@0 166 protected function getRequestConstraint($path) {
Chris@0 167 return $this->callback(function (Request $request) use ($path) {
Chris@0 168 return $request->getPathInfo() == $path;
Chris@0 169 });
Chris@0 170 }
Chris@0 171
Chris@0 172 /**
Chris@0 173 * Tests the fromRoute() method with the special <front> path.
Chris@0 174 *
Chris@0 175 * @covers ::fromRoute
Chris@0 176 */
Chris@0 177 public function testFromRouteFront() {
Chris@0 178 $url = Url::fromRoute('<front>');
Chris@0 179 $this->assertSame('<front>', $url->getRouteName());
Chris@0 180 }
Chris@0 181
Chris@0 182 /**
Chris@0 183 * Tests the fromUserInput method with valid paths.
Chris@0 184 *
Chris@0 185 * @covers ::fromUserInput
Chris@0 186 * @dataProvider providerFromValidInternalUri
Chris@0 187 */
Chris@0 188 public function testFromUserInput($path) {
Chris@0 189 $url = Url::fromUserInput($path);
Chris@0 190 $uri = $url->getUri();
Chris@0 191
Chris@0 192 $this->assertInstanceOf('Drupal\Core\Url', $url);
Chris@0 193 $this->assertFalse($url->isRouted());
Chris@0 194 $this->assertEquals(0, strpos($uri, 'base:'));
Chris@0 195
Chris@0 196 $parts = UrlHelper::parse($path);
Chris@0 197 $options = $url->getOptions();
Chris@0 198
Chris@0 199 if (!empty($parts['fragment'])) {
Chris@0 200 $this->assertSame($parts['fragment'], $options['fragment']);
Chris@0 201 }
Chris@0 202 else {
Chris@0 203 $this->assertArrayNotHasKey('fragment', $options);
Chris@0 204 }
Chris@0 205
Chris@0 206 if (!empty($parts['query'])) {
Chris@0 207 $this->assertEquals($parts['query'], $options['query']);
Chris@0 208 }
Chris@0 209 else {
Chris@0 210 $this->assertArrayNotHasKey('query', $options);
Chris@0 211 }
Chris@0 212 }
Chris@0 213
Chris@0 214 /**
Chris@0 215 * Tests the fromUserInput method with invalid paths.
Chris@0 216 *
Chris@0 217 * @covers ::fromUserInput
Chris@0 218 * @dataProvider providerFromInvalidInternalUri
Chris@0 219 */
Chris@0 220 public function testFromInvalidUserInput($path) {
Chris@0 221 $this->setExpectedException(\InvalidArgumentException::class);
Chris@0 222 $url = Url::fromUserInput($path);
Chris@0 223 }
Chris@0 224
Chris@0 225 /**
Chris@0 226 * Tests fromUri() method with a user-entered path not matching any route.
Chris@0 227 *
Chris@0 228 * @covers ::fromUri
Chris@0 229 */
Chris@0 230 public function testFromRoutedPathWithInvalidRoute() {
Chris@0 231 $this->pathValidator->expects($this->once())
Chris@0 232 ->method('getUrlIfValidWithoutAccessCheck')
Chris@0 233 ->with('invalid-path')
Chris@0 234 ->willReturn(FALSE);
Chris@0 235 $url = Url::fromUri('internal:/invalid-path');
Chris@0 236 $this->assertSame(FALSE, $url->isRouted());
Chris@0 237 $this->assertSame('base:invalid-path', $url->getUri());
Chris@0 238 }
Chris@0 239
Chris@0 240 /**
Chris@0 241 * Tests fromUri() method with user-entered path matching a valid route.
Chris@0 242 *
Chris@0 243 * @covers ::fromUri
Chris@0 244 */
Chris@0 245 public function testFromRoutedPathWithValidRoute() {
Chris@0 246 $url = Url::fromRoute('test_route');
Chris@0 247 $this->pathValidator->expects($this->once())
Chris@0 248 ->method('getUrlIfValidWithoutAccessCheck')
Chris@0 249 ->with('valid-path')
Chris@0 250 ->willReturn($url);
Chris@0 251 $result_url = Url::fromUri('internal:/valid-path');
Chris@0 252 $this->assertSame($url, $result_url);
Chris@0 253 }
Chris@0 254
Chris@0 255 /**
Chris@0 256 * Tests the createFromRequest method.
Chris@0 257 *
Chris@0 258 * @covers ::createFromRequest
Chris@0 259 */
Chris@0 260 public function testCreateFromRequest() {
Chris@0 261 $attributes = [
Chris@0 262 '_raw_variables' => new ParameterBag([
Chris@0 263 'color' => 'chartreuse',
Chris@0 264 ]),
Chris@0 265 RouteObjectInterface::ROUTE_NAME => 'the_route_name',
Chris@0 266 ];
Chris@0 267 $request = new Request([], [], $attributes);
Chris@0 268
Chris@0 269 $this->router->expects($this->once())
Chris@0 270 ->method('matchRequest')
Chris@0 271 ->with($request)
Chris@0 272 ->will($this->returnValue($attributes));
Chris@0 273
Chris@0 274 $url = Url::createFromRequest($request);
Chris@0 275 $expected = new Url('the_route_name', ['color' => 'chartreuse']);
Chris@0 276 $this->assertEquals($expected, $url);
Chris@0 277 }
Chris@0 278
Chris@0 279 /**
Chris@0 280 * Tests that an invalid request will thrown an exception.
Chris@0 281 *
Chris@0 282 * @covers ::createFromRequest
Chris@0 283 */
Chris@0 284 public function testUrlFromRequestInvalid() {
Chris@0 285 $request = Request::create('/test-path');
Chris@0 286
Chris@0 287 $this->router->expects($this->once())
Chris@0 288 ->method('matchRequest')
Chris@0 289 ->with($request)
Chris@0 290 ->will($this->throwException(new ResourceNotFoundException()));
Chris@0 291
Chris@0 292 $this->setExpectedException(ResourceNotFoundException::class);
Chris@0 293 Url::createFromRequest($request);
Chris@0 294 }
Chris@0 295
Chris@0 296 /**
Chris@0 297 * Tests the isExternal() method.
Chris@0 298 *
Chris@0 299 * @depends testUrlFromRequest
Chris@0 300 *
Chris@0 301 * @covers ::isExternal
Chris@0 302 */
Chris@0 303 public function testIsExternal($urls) {
Chris@0 304 foreach ($urls as $url) {
Chris@0 305 $this->assertFalse($url->isExternal());
Chris@0 306 }
Chris@0 307 }
Chris@0 308
Chris@0 309 /**
Chris@0 310 * Tests the getUri() method for internal URLs.
Chris@0 311 *
Chris@0 312 * @param \Drupal\Core\Url[] $urls
Chris@0 313 * Array of URL objects.
Chris@0 314 *
Chris@0 315 * @depends testUrlFromRequest
Chris@0 316 *
Chris@0 317 * @covers ::getUri
Chris@0 318 */
Chris@0 319 public function testGetUriForInternalUrl($urls) {
Chris@0 320 $this->setExpectedException(\UnexpectedValueException::class);
Chris@0 321 foreach ($urls as $url) {
Chris@0 322 $url->getUri();
Chris@0 323 }
Chris@0 324 }
Chris@0 325
Chris@0 326 /**
Chris@0 327 * Tests the getUri() method for external URLs.
Chris@0 328 *
Chris@0 329 * @covers ::getUri
Chris@0 330 */
Chris@0 331 public function testGetUriForExternalUrl() {
Chris@0 332 $url = Url::fromUri('http://example.com/test');
Chris@0 333 $this->assertEquals('http://example.com/test', $url->getUri());
Chris@0 334 }
Chris@0 335
Chris@0 336 /**
Chris@0 337 * Tests the getUri() and isExternal() methods for protocol-relative URLs.
Chris@0 338 *
Chris@0 339 * @covers ::getUri
Chris@0 340 * @covers ::isExternal
Chris@0 341 */
Chris@0 342 public function testGetUriForProtocolRelativeUrl() {
Chris@0 343 $url = Url::fromUri('//example.com/test');
Chris@0 344 $this->assertEquals('//example.com/test', $url->getUri());
Chris@0 345 $this->assertTrue($url->isExternal());
Chris@0 346 }
Chris@0 347
Chris@0 348 /**
Chris@0 349 * Tests the getInternalPath method().
Chris@0 350 *
Chris@0 351 * @param \Drupal\Core\Url[] $urls
Chris@0 352 * Array of URL objects.
Chris@0 353 *
Chris@0 354 * @covers ::getInternalPath
Chris@0 355 *
Chris@0 356 * @depends testUrlFromRequest
Chris@0 357 */
Chris@0 358 public function testGetInternalPath($urls) {
Chris@0 359 $map = [];
Chris@0 360 $map[] = ['view.frontpage.page_1', [], '/node'];
Chris@0 361 $map[] = ['node_view', ['node' => '1'], '/node/1'];
Chris@0 362 $map[] = ['node_edit', ['node' => '2'], '/node/2/edit'];
Chris@0 363
Chris@0 364 foreach ($urls as $index => $url) {
Chris@0 365 // Clone the url so that there is no leak of internal state into the
Chris@0 366 // other ones.
Chris@0 367 $url = clone $url;
Chris@0 368 $url_generator = $this->getMock('Drupal\Core\Routing\UrlGeneratorInterface');
Chris@0 369 $url_generator->expects($this->once())
Chris@0 370 ->method('getPathFromRoute')
Chris@0 371 ->will($this->returnValueMap($map, $index));
Chris@0 372 $url->setUrlGenerator($url_generator);
Chris@0 373
Chris@0 374 $url->getInternalPath();
Chris@0 375 $url->getInternalPath();
Chris@0 376 }
Chris@0 377 }
Chris@0 378
Chris@0 379 /**
Chris@0 380 * Tests the toString() method.
Chris@0 381 *
Chris@0 382 * @param \Drupal\Core\Url[] $urls
Chris@0 383 * An array of Url objects.
Chris@0 384 *
Chris@0 385 * @depends testUrlFromRequest
Chris@0 386 *
Chris@0 387 * @covers ::toString
Chris@0 388 */
Chris@0 389 public function testToString($urls) {
Chris@0 390 foreach ($urls as $index => $url) {
Chris@0 391 $path = array_pop($this->map[$index]);
Chris@0 392 $this->assertSame($path, $url->toString());
Chris@0 393 $generated_url = $url->toString(TRUE);
Chris@0 394 $this->assertSame($path, $generated_url->getGeneratedUrl());
Chris@0 395 $this->assertInstanceOf('\Drupal\Core\Render\BubbleableMetadata', $generated_url);
Chris@0 396 }
Chris@0 397 }
Chris@0 398
Chris@0 399 /**
Chris@0 400 * Tests the getRouteName() method.
Chris@0 401 *
Chris@0 402 * @param \Drupal\Core\Url[] $urls
Chris@0 403 * An array of Url objects.
Chris@0 404 *
Chris@0 405 * @depends testUrlFromRequest
Chris@0 406 *
Chris@0 407 * @covers ::getRouteName
Chris@0 408 */
Chris@0 409 public function testGetRouteName($urls) {
Chris@0 410 foreach ($urls as $index => $url) {
Chris@0 411 $this->assertSame($this->map[$index][0], $url->getRouteName());
Chris@0 412 }
Chris@0 413 }
Chris@0 414
Chris@0 415 /**
Chris@0 416 * Tests the getRouteName() with an external URL.
Chris@0 417 *
Chris@0 418 * @covers ::getRouteName
Chris@0 419 */
Chris@0 420 public function testGetRouteNameWithExternalUrl() {
Chris@0 421 $url = Url::fromUri('http://example.com');
Chris@0 422 $this->setExpectedException(\UnexpectedValueException::class);
Chris@0 423 $url->getRouteName();
Chris@0 424 }
Chris@0 425
Chris@0 426 /**
Chris@0 427 * Tests the getRouteParameters() method.
Chris@0 428 *
Chris@0 429 * @param \Drupal\Core\Url[] $urls
Chris@0 430 * An array of Url objects.
Chris@0 431 *
Chris@0 432 * @depends testUrlFromRequest
Chris@0 433 *
Chris@0 434 * @covers ::getRouteParameters
Chris@0 435 */
Chris@0 436 public function testGetRouteParameters($urls) {
Chris@0 437 foreach ($urls as $index => $url) {
Chris@0 438 $this->assertSame($this->map[$index][1], $url->getRouteParameters());
Chris@0 439 }
Chris@0 440 }
Chris@0 441
Chris@0 442 /**
Chris@0 443 * Tests the getRouteParameters() with an external URL.
Chris@0 444 *
Chris@0 445 * @covers ::getRouteParameters
Chris@0 446 */
Chris@0 447 public function testGetRouteParametersWithExternalUrl() {
Chris@0 448 $url = Url::fromUri('http://example.com');
Chris@0 449 $this->setExpectedException(\UnexpectedValueException::class);
Chris@0 450 $url->getRouteParameters();
Chris@0 451 }
Chris@0 452
Chris@0 453 /**
Chris@0 454 * Tests the getOptions() method.
Chris@0 455 *
Chris@0 456 * @param \Drupal\Core\Url[] $urls
Chris@0 457 * An array of Url objects.
Chris@0 458 *
Chris@0 459 * @depends testUrlFromRequest
Chris@0 460 *
Chris@0 461 * @covers ::getOptions
Chris@0 462 */
Chris@0 463 public function testGetOptions($urls) {
Chris@0 464 foreach ($urls as $index => $url) {
Chris@0 465 $this->assertSame($this->map[$index][2], $url->getOptions());
Chris@0 466 }
Chris@0 467 }
Chris@0 468
Chris@0 469 /**
Chris@0 470 * Tests the setOptions() method.
Chris@0 471 *
Chris@0 472 * @covers ::setOptions
Chris@0 473 */
Chris@0 474 public function testSetOptions() {
Chris@0 475 $url = Url::fromRoute('test_route', []);
Chris@0 476 $this->assertEquals([], $url->getOptions());
Chris@0 477 $url->setOptions(['foo' => 'bar']);
Chris@0 478 $this->assertEquals(['foo' => 'bar'], $url->getOptions());
Chris@0 479 $url->setOptions([]);
Chris@0 480 $this->assertEquals([], $url->getOptions());
Chris@0 481 }
Chris@0 482
Chris@0 483 /**
Chris@0 484 * Tests the mergeOptions() method.
Chris@0 485 *
Chris@0 486 * @covers ::mergeOptions
Chris@0 487 */
Chris@0 488 public function testMergeOptions() {
Chris@0 489 $url = Url::fromRoute('test_route', [], ['foo' => 'bar', 'bar' => ['key' => 'value']]);
Chris@0 490 $url->mergeOptions(['bar' => ['key' => 'value1', 'key2' => 'value2']]);
Chris@0 491 $this->assertEquals(['foo' => 'bar', 'bar' => ['key' => 'value1', 'key2' => 'value2']], $url->getOptions());
Chris@0 492 }
Chris@0 493
Chris@0 494 /**
Chris@0 495 * Tests the access() method for routed URLs.
Chris@0 496 *
Chris@0 497 * @param bool $access
Chris@0 498 *
Chris@0 499 * @covers ::access
Chris@0 500 * @covers ::accessManager
Chris@0 501 * @dataProvider accessProvider
Chris@0 502 */
Chris@0 503 public function testAccessRouted($access) {
Chris@0 504 $account = $this->getMock('Drupal\Core\Session\AccountInterface');
Chris@0 505 $url = new TestUrl('entity.node.canonical', ['node' => 3]);
Chris@0 506 $url->setAccessManager($this->getMockAccessManager($access, $account));
Chris@0 507 $this->assertEquals($access, $url->access($account));
Chris@0 508 }
Chris@0 509
Chris@0 510 /**
Chris@0 511 * Tests the access() method for unrouted URLs (they always have access).
Chris@0 512 *
Chris@0 513 * @covers ::access
Chris@0 514 */
Chris@0 515 public function testAccessUnrouted() {
Chris@0 516 $account = $this->getMock('Drupal\Core\Session\AccountInterface');
Chris@0 517 $url = TestUrl::fromUri('base:kittens');
Chris@0 518 $access_manager = $this->getMock('Drupal\Core\Access\AccessManagerInterface');
Chris@0 519 $access_manager->expects($this->never())
Chris@0 520 ->method('checkNamedRoute');
Chris@0 521 $url->setAccessManager($access_manager);
Chris@0 522 $this->assertTrue($url->access($account));
Chris@0 523 }
Chris@0 524
Chris@0 525 /**
Chris@0 526 * Tests the renderAccess() method.
Chris@0 527 *
Chris@0 528 * @param bool $access
Chris@0 529 *
Chris@0 530 * @covers ::renderAccess
Chris@0 531 * @dataProvider accessProvider
Chris@0 532 */
Chris@0 533 public function testRenderAccess($access) {
Chris@0 534 $element = [
Chris@0 535 '#url' => Url::fromRoute('entity.node.canonical', ['node' => 3]),
Chris@0 536 ];
Chris@0 537 $this->container->set('current_user', $this->getMock('Drupal\Core\Session\AccountInterface'));
Chris@0 538 $this->container->set('access_manager', $this->getMockAccessManager($access));
Chris@0 539 $this->assertEquals($access, TestUrl::renderAccess($element));
Chris@0 540 }
Chris@0 541
Chris@0 542 /**
Chris@0 543 * Tests the fromRouteMatch() method.
Chris@0 544 */
Chris@0 545 public function testFromRouteMatch() {
Chris@0 546 $route = new Route('/test-route/{foo}');
Chris@0 547 $route_match = new RouteMatch('test_route', $route, ['foo' => (object) [1]], ['foo' => 1]);
Chris@0 548 $url = Url::fromRouteMatch($route_match);
Chris@0 549 $this->assertSame('test_route', $url->getRouteName());
Chris@0 550 $this->assertEquals(['foo' => '1'], $url->getRouteParameters());
Chris@0 551 }
Chris@0 552
Chris@0 553 /**
Chris@0 554 * Data provider for testing entity URIs
Chris@0 555 */
Chris@0 556 public function providerTestEntityUris() {
Chris@0 557 return [
Chris@0 558 [
Chris@0 559 'entity:test_entity/1',
Chris@0 560 [],
Chris@0 561 'entity.test_entity.canonical',
Chris@0 562 ['test_entity' => '1'],
Chris@0 563 NULL,
Chris@0 564 NULL,
Chris@0 565 ],
Chris@0 566 [
Chris@0 567 // Ensure a fragment of #0 is handled correctly.
Chris@0 568 'entity:test_entity/1#0',
Chris@0 569 [],
Chris@0 570 'entity.test_entity.canonical',
Chris@0 571 ['test_entity' => '1'],
Chris@0 572 NULL,
Chris@0 573 '0',
Chris@0 574 ],
Chris@0 575 // Ensure an empty fragment of # is in options discarded as expected.
Chris@0 576 [
Chris@0 577 'entity:test_entity/1',
Chris@0 578 ['fragment' => ''],
Chris@0 579 'entity.test_entity.canonical',
Chris@0 580 ['test_entity' => '1'],
Chris@0 581 NULL,
Chris@0 582 NULL,
Chris@0 583 ],
Chris@0 584 // Ensure an empty fragment of # in the URI is discarded as expected.
Chris@0 585 [
Chris@0 586 'entity:test_entity/1#',
Chris@0 587 [],
Chris@0 588 'entity.test_entity.canonical',
Chris@0 589 ['test_entity' => '1'],
Chris@0 590 NULL,
Chris@0 591 NULL,
Chris@0 592 ],
Chris@0 593 [
Chris@0 594 'entity:test_entity/2?page=1&foo=bar#bottom',
Chris@0 595 [], 'entity.test_entity.canonical',
Chris@0 596 ['test_entity' => '2'],
Chris@0 597 ['page' => '1', 'foo' => 'bar'],
Chris@0 598 'bottom',
Chris@0 599 ],
Chris@0 600 [
Chris@0 601 'entity:test_entity/2?page=1&foo=bar#bottom',
Chris@0 602 ['fragment' => 'top', 'query' => ['foo' => 'yes', 'focus' => 'no']],
Chris@0 603 'entity.test_entity.canonical',
Chris@0 604 ['test_entity' => '2'],
Chris@0 605 ['page' => '1', 'foo' => 'yes', 'focus' => 'no'],
Chris@0 606 'top',
Chris@0 607 ],
Chris@0 608
Chris@0 609 ];
Chris@0 610 }
Chris@0 611
Chris@0 612 /**
Chris@0 613 * Tests the fromUri() method with an entity: URI.
Chris@0 614 *
Chris@0 615 * @covers ::fromUri
Chris@0 616 *
Chris@0 617 * @dataProvider providerTestEntityUris
Chris@0 618 */
Chris@0 619 public function testEntityUris($uri, $options, $route_name, $route_parameters, $query, $fragment) {
Chris@0 620 $url = Url::fromUri($uri, $options);
Chris@0 621 $this->assertSame($route_name, $url->getRouteName());
Chris@0 622 $this->assertEquals($route_parameters, $url->getRouteParameters());
Chris@0 623 $this->assertEquals($url->getOption('query'), $query);
Chris@0 624 $this->assertSame($url->getOption('fragment'), $fragment);
Chris@0 625 }
Chris@0 626
Chris@0 627 /**
Chris@0 628 * Tests the fromUri() method with an invalid entity: URI.
Chris@0 629 *
Chris@0 630 * @covers ::fromUri
Chris@0 631 */
Chris@0 632 public function testInvalidEntityUriParameter() {
Chris@0 633 // Make the mocked URL generator behave like the actual one.
Chris@0 634 $this->urlGenerator->expects($this->once())
Chris@0 635 ->method('generateFromRoute')
Chris@0 636 ->with('entity.test_entity.canonical', ['test_entity' => '1/blah'])
Chris@0 637 ->willThrowException(new InvalidParameterException('Parameter "test_entity" for route "/test_entity/{test_entity}" must match "[^/]++" ("1/blah" given) to generate a corresponding URL..'));
Chris@0 638
Chris@0 639 $this->setExpectedException(InvalidParameterException::class);
Chris@0 640 Url::fromUri('entity:test_entity/1/blah')->toString();
Chris@0 641 }
Chris@0 642
Chris@0 643 /**
Chris@0 644 * Tests the toUriString() method with entity: URIs.
Chris@0 645 *
Chris@0 646 * @covers ::toUriString
Chris@0 647 *
Chris@0 648 * @dataProvider providerTestToUriStringForEntity
Chris@0 649 */
Chris@0 650 public function testToUriStringForEntity($uri, $options, $uri_string) {
Chris@0 651 $url = Url::fromUri($uri, $options);
Chris@0 652 $this->assertSame($url->toUriString(), $uri_string);
Chris@0 653 }
Chris@0 654
Chris@0 655 /**
Chris@0 656 * Data provider for testing string entity URIs
Chris@0 657 */
Chris@0 658 public function providerTestToUriStringForEntity() {
Chris@0 659 return [
Chris@0 660 ['entity:test_entity/1', [], 'route:entity.test_entity.canonical;test_entity=1'],
Chris@0 661 ['entity:test_entity/1', ['fragment' => 'top', 'query' => ['page' => '2']], 'route:entity.test_entity.canonical;test_entity=1?page=2#top'],
Chris@0 662 ['entity:test_entity/1?page=2#top', [], 'route:entity.test_entity.canonical;test_entity=1?page=2#top'],
Chris@0 663 ];
Chris@0 664 }
Chris@0 665
Chris@0 666 /**
Chris@0 667 * Tests the toUriString() method with internal: URIs.
Chris@0 668 *
Chris@0 669 * @covers ::toUriString
Chris@0 670 *
Chris@0 671 * @dataProvider providerTestToUriStringForInternal
Chris@0 672 */
Chris@0 673 public function testToUriStringForInternal($uri, $options, $uri_string) {
Chris@0 674 $url = Url::fromRoute('entity.test_entity.canonical', ['test_entity' => '1']);
Chris@0 675 $this->pathValidator->expects($this->any())
Chris@0 676 ->method('getUrlIfValidWithoutAccessCheck')
Chris@0 677 ->willReturnMap([
Chris@0 678 ['test-entity/1', $url],
Chris@0 679 ['<front>', Url::fromRoute('<front>')],
Chris@0 680 ['<none>', Url::fromRoute('<none>')],
Chris@0 681 ]);
Chris@0 682 $url = Url::fromUri($uri, $options);
Chris@0 683 $this->assertSame($url->toUriString(), $uri_string);
Chris@0 684 }
Chris@0 685
Chris@0 686 /**
Chris@0 687 * Data provider for testing internal URIs.
Chris@0 688 */
Chris@0 689 public function providerTestToUriStringForInternal() {
Chris@0 690 return [
Chris@0 691 // The four permutations of a regular path.
Chris@0 692 ['internal:/test-entity/1', [], 'route:entity.test_entity.canonical;test_entity=1'],
Chris@0 693 ['internal:/test-entity/1', ['fragment' => 'top'], 'route:entity.test_entity.canonical;test_entity=1#top'],
Chris@0 694 ['internal:/test-entity/1', ['fragment' => 'top', 'query' => ['page' => '2']], 'route:entity.test_entity.canonical;test_entity=1?page=2#top'],
Chris@0 695 ['internal:/test-entity/1?page=2#top', [], 'route:entity.test_entity.canonical;test_entity=1?page=2#top'],
Chris@0 696
Chris@0 697 // The four permutations of the special '<front>' path.
Chris@0 698 ['internal:/', [], 'route:<front>'],
Chris@0 699 ['internal:/', ['fragment' => 'top'], 'route:<front>#top'],
Chris@0 700 ['internal:/', ['fragment' => 'top', 'query' => ['page' => '2']], 'route:<front>?page=2#top'],
Chris@0 701 ['internal:/?page=2#top', [], 'route:<front>?page=2#top'],
Chris@0 702
Chris@0 703 // The four permutations of the special '<none>' path.
Chris@0 704 ['internal:', [], 'route:<none>'],
Chris@0 705 ['internal:', ['fragment' => 'top'], 'route:<none>#top'],
Chris@0 706 ['internal:', ['fragment' => 'top', 'query' => ['page' => '2']], 'route:<none>?page=2#top'],
Chris@0 707 ['internal:?page=2#top', [], 'route:<none>?page=2#top'],
Chris@0 708 ];
Chris@0 709 }
Chris@0 710
Chris@0 711 /**
Chris@0 712 * Tests the fromUri() method with a valid internal: URI.
Chris@0 713 *
Chris@0 714 * @covers ::fromUri
Chris@0 715 * @dataProvider providerFromValidInternalUri
Chris@0 716 */
Chris@0 717 public function testFromValidInternalUri($path) {
Chris@0 718 $url = Url::fromUri('internal:' . $path);
Chris@0 719 $this->assertInstanceOf('Drupal\Core\Url', $url);
Chris@0 720 }
Chris@0 721
Chris@0 722 /**
Chris@0 723 * Data provider for testFromValidInternalUri().
Chris@0 724 */
Chris@0 725 public function providerFromValidInternalUri() {
Chris@0 726 return [
Chris@0 727 // Normal paths with a leading slash.
Chris@0 728 ['/kittens'],
Chris@0 729 ['/kittens/bengal'],
Chris@0 730 // Fragments with and without leading slashes.
Chris@0 731 ['/#about-our-kittens'],
Chris@0 732 ['/kittens#feeding'],
Chris@0 733 ['#feeding'],
Chris@0 734 // Query strings with and without leading slashes.
Chris@0 735 ['/kittens?page=1000'],
Chris@0 736 ['/?page=1000'],
Chris@0 737 ['?page=1000'],
Chris@0 738 ['?breed=bengal&page=1000'],
Chris@0 739 ['?referrer=https://kittenfacts'],
Chris@0 740 // Paths with various token formats but no leading slash.
Chris@0 741 ['/[duckies]'],
Chris@0 742 ['/%bunnies'],
Chris@0 743 ['/{{ puppies }}'],
Chris@0 744 // Disallowed characters in the authority (host name) that are valid
Chris@0 745 // elsewhere in the path.
Chris@0 746 ['/(:;2&+h^'],
Chris@0 747 ['/AKI@&hO@'],
Chris@0 748 ];
Chris@0 749 }
Chris@0 750
Chris@0 751 /**
Chris@0 752 * Tests the fromUri() method with an invalid internal: URI.
Chris@0 753 *
Chris@0 754 * @covers ::fromUri
Chris@0 755 * @dataProvider providerFromInvalidInternalUri
Chris@0 756 */
Chris@0 757 public function testFromInvalidInternalUri($path) {
Chris@0 758 $this->setExpectedException(\InvalidArgumentException::class);
Chris@0 759 Url::fromUri('internal:' . $path);
Chris@0 760 }
Chris@0 761
Chris@0 762 /**
Chris@0 763 * Data provider for testFromInvalidInternalUri().
Chris@0 764 */
Chris@0 765 public function providerFromInvalidInternalUri() {
Chris@0 766 return [
Chris@0 767 // Normal paths without a leading slash.
Chris@0 768 'normal_path0' => ['kittens'],
Chris@0 769 'normal_path1' => ['kittens/bengal'],
Chris@0 770 // Path without a leading slash containing a fragment.
Chris@0 771 'fragment' => ['kittens#feeding'],
Chris@0 772 // Path without a leading slash containing a query string.
Chris@0 773 'without_leading_slash_query' => ['kittens?page=1000'],
Chris@0 774 // Paths with various token formats but no leading slash.
Chris@0 775 'path_with_tokens0' => ['[duckies]'],
Chris@0 776 'path_with_tokens1' => ['%bunnies'],
Chris@0 777 'path_with_tokens2' => ['{{ puppies }}'],
Chris@0 778 // Disallowed characters in the authority (host name) that are valid
Chris@0 779 // elsewhere in the path.
Chris@0 780 'disallowed_hostname_chars0' => ['(:;2&+h^'],
Chris@0 781 'disallowed_hostname_chars1' => ['AKI@&hO@'],
Chris@0 782 // Leading slash with a domain.
Chris@0 783 'leading_slash_with_domain' => ['/http://example.com'],
Chris@0 784 ];
Chris@0 785 }
Chris@0 786
Chris@0 787 /**
Chris@0 788 * Tests the fromUri() method with a base: URI starting with a number.
Chris@0 789 *
Chris@0 790 * @covers ::fromUri
Chris@0 791 */
Chris@0 792 public function testFromUriNumber() {
Chris@0 793 $url = Url::fromUri('base:2015/10/06');
Chris@0 794 $this->assertSame($url->toUriString(), 'base:/2015/10/06');
Chris@0 795 }
Chris@0 796
Chris@0 797 /**
Chris@0 798 * Tests the toUriString() method with route: URIs.
Chris@0 799 *
Chris@0 800 * @covers ::toUriString
Chris@0 801 *
Chris@0 802 * @dataProvider providerTestToUriStringForRoute
Chris@0 803 */
Chris@0 804 public function testToUriStringForRoute($uri, $options, $uri_string) {
Chris@0 805 $url = Url::fromUri($uri, $options);
Chris@0 806 $this->assertSame($url->toUriString(), $uri_string);
Chris@0 807 }
Chris@0 808
Chris@0 809 /**
Chris@0 810 * Data provider for testing route: URIs.
Chris@0 811 */
Chris@0 812 public function providerTestToUriStringForRoute() {
Chris@0 813 return [
Chris@0 814 ['route:entity.test_entity.canonical;test_entity=1', [], 'route:entity.test_entity.canonical;test_entity=1'],
Chris@0 815 ['route:entity.test_entity.canonical;test_entity=1', ['fragment' => 'top', 'query' => ['page' => '2']], 'route:entity.test_entity.canonical;test_entity=1?page=2#top'],
Chris@0 816 ['route:entity.test_entity.canonical;test_entity=1?page=2#top', [], 'route:entity.test_entity.canonical;test_entity=1?page=2#top'],
Chris@0 817 // Check that an empty fragment is discarded.
Chris@0 818 ['route:entity.test_entity.canonical;test_entity=1?page=2#', [], 'route:entity.test_entity.canonical;test_entity=1?page=2'],
Chris@0 819 // Check that an empty fragment is discarded.
Chris@0 820 ['route:entity.test_entity.canonical;test_entity=1?page=2', ['fragment' => ''], 'route:entity.test_entity.canonical;test_entity=1?page=2'],
Chris@0 821 // Check that a fragment of #0 is preserved.
Chris@0 822 ['route:entity.test_entity.canonical;test_entity=1?page=2#0', [], 'route:entity.test_entity.canonical;test_entity=1?page=2#0'],
Chris@0 823 ];
Chris@0 824 }
Chris@0 825
Chris@0 826 /**
Chris@0 827 * @covers ::fromUri
Chris@0 828 */
Chris@0 829 public function testFromRouteUriWithMissingRouteName() {
Chris@0 830 $this->setExpectedException(\InvalidArgumentException::class, "The route URI 'route:' is invalid.");
Chris@0 831 Url::fromUri('route:');
Chris@0 832 }
Chris@0 833
Chris@0 834 /**
Chris@0 835 * Creates a mock access manager for the access tests.
Chris@0 836 *
Chris@0 837 * @param bool $access
Chris@0 838 * @param \Drupal\Core\Session\AccountInterface|null $account
Chris@0 839 *
Chris@0 840 * @return \Drupal\Core\Access\AccessManagerInterface|\PHPUnit_Framework_MockObject_MockObject
Chris@0 841 */
Chris@0 842 protected function getMockAccessManager($access, $account = NULL) {
Chris@0 843 $access_manager = $this->getMock('Drupal\Core\Access\AccessManagerInterface');
Chris@0 844 $access_manager->expects($this->once())
Chris@0 845 ->method('checkNamedRoute')
Chris@0 846 ->with('entity.node.canonical', ['node' => 3], $account)
Chris@0 847 ->willReturn($access);
Chris@0 848 return $access_manager;
Chris@0 849 }
Chris@0 850
Chris@0 851 /**
Chris@0 852 * Data provider for the access test methods.
Chris@0 853 */
Chris@0 854 public function accessProvider() {
Chris@0 855 return [
Chris@0 856 [TRUE],
Chris@0 857 [FALSE],
Chris@0 858 ];
Chris@0 859 }
Chris@0 860
Chris@0 861 }
Chris@0 862
Chris@0 863 class TestUrl extends Url {
Chris@0 864
Chris@0 865 /**
Chris@0 866 * Sets the access manager.
Chris@0 867 *
Chris@0 868 * @param \Drupal\Core\Access\AccessManagerInterface $access_manager
Chris@0 869 */
Chris@0 870 public function setAccessManager(AccessManagerInterface $access_manager) {
Chris@0 871 $this->accessManager = $access_manager;
Chris@0 872 }
Chris@0 873
Chris@0 874 }