View source
<?php
namespace Drupal\Tests\Core\Routing;
use Drupal\accept_header_routing_test\Routing\AcceptHeaderMatcher;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
class AcceptHeaderMatcherTest extends UnitTestCase {
protected $fixtures;
protected $matcher;
protected function setUp() {
parent::setUp();
$this->fixtures = new RoutingFixtures();
$this->matcher = new AcceptHeaderMatcher();
}
public function acceptFilterProvider() {
return [
[
'application/json, text/xml;q=0.9',
'json',
'route_c',
'route_e',
],
[
'application/x-json, text/xml;q=0.9',
'json',
'route_c',
'route_e',
],
[
'text/html, text/xml;q=0.9',
'html',
'route_e',
'route_c',
],
];
}
public function testAcceptFiltering($accept_header, $format, $included_route, $excluded_route) {
$collection = $this->fixtures
->sampleRouteCollection();
$request = Request::create('path/two', 'GET');
$request->headers
->set('Accept', $accept_header);
$request
->setRequestFormat($format);
$routes = $this->matcher
->filter($collection, $request);
$this
->assertCount(4, $routes, 'The correct number of routes was found.');
$this
->assertNotNull($routes
->get($included_route), "Route {$included_route} was found when matching {$accept_header}.");
$this
->assertNull($routes
->get($excluded_route), "Route {$excluded_route} was not found when matching {$accept_header}.");
foreach ($routes as $name => $route) {
$this
->assertEquals($name, $included_route, "Route {$included_route} is the first one in the collection when matching {$accept_header}.");
break;
}
}
public function testNoRouteFound() {
$routes = $this->fixtures
->sampleRouteCollection();
$routes
->remove('route_a');
$routes
->remove('route_b');
$routes
->remove('route_c');
$routes
->remove('route_d');
$request = Request::create('path/two', 'GET');
$request->headers
->set('Accept', 'application/json, text/xml;q=0.9');
$request
->setRequestFormat('json');
$this
->expectException(NotAcceptableHttpException::class);
$this
->expectExceptionMessage('No route found for the specified formats application/json text/xml');
$this->matcher
->filter($routes, $request);
}
}