Issue #3490710 by mfb: Catch potential exception when calling Request::create() in PathBasedBreadcrumbBuilder

(cherry picked from commit d034f55802)
merge-requests/10503/head
catch 2024-12-02 12:48:18 +00:00
parent 9a90e5e0ce
commit c44c9a2ece
2 changed files with 29 additions and 1 deletions

View File

@ -20,6 +20,7 @@ use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@ -211,7 +212,12 @@ class PathBasedBreadcrumbBuilder implements BreadcrumbBuilderInterface {
if (!empty($exclude[$path])) {
return NULL;
}
$request = Request::create($path);
try {
$request = Request::create($path);
}
catch (BadRequestException) {
return NULL;
}
// Performance optimization: set a short accept header to reduce overhead in
// AcceptHeaderMatcher when matching the request.
$request->headers->set('Accept', 'text/html');

View File

@ -336,6 +336,28 @@ class PathBasedBreadcrumbBuilderTest extends UnitTestCase {
$this->assertEquals(Cache::PERMANENT, $breadcrumb->getCacheMaxAge());
}
/**
* Tests the build method with an invalid path.
*
* @covers ::build
* @covers ::getRequestForPath
*/
public function testBuildWithInvalidPath(): void {
// The parse_url() function returns FALSE for '/:123/foo' so the
// Request::create() method therefore considers it to be an invalid URI.
$this->context->expects($this->once())
->method('getPathInfo')
->willReturn('/:123/foo/bar');
$breadcrumb = $this->builder->build($this->createMock('Drupal\Core\Routing\RouteMatchInterface'));
// No path matched, though at least the frontpage is displayed.
$this->assertEquals([0 => new Link('Home', new Url('<front>'))], $breadcrumb->getLinks());
$this->assertEqualsCanonicalizing(['url.path.is_front', 'url.path.parent'], $breadcrumb->getCacheContexts());
$this->assertEqualsCanonicalizing([], $breadcrumb->getCacheTags());
$this->assertEquals(Cache::PERMANENT, $breadcrumb->getCacheMaxAge());
}
/**
* Tests the applied method.
*