From 996b3578a4b021678da153bc28efaaccb665e23c Mon Sep 17 00:00:00 2001
From: catch <catch@35733.no-reply.drupal.org>
Date: Wed, 12 May 2021 21:25:38 +0100
Subject: [PATCH] Issue #3210372 by pfrenssen, claudiu.cristea: Fatal error
 when passing non-existing ID to entity parameter converter

---
 core/lib/Drupal/Core/ParamConverter/EntityConverter.php    | 7 ++++++-
 .../Core/ParamConverter/EntityConverterTest.php            | 6 ++++++
 2 files changed, 12 insertions(+), 1 deletion(-)

diff --git a/core/lib/Drupal/Core/ParamConverter/EntityConverter.php b/core/lib/Drupal/Core/ParamConverter/EntityConverter.php
index 939757fd1e19..515517b91129 100644
--- a/core/lib/Drupal/Core/ParamConverter/EntityConverter.php
+++ b/core/lib/Drupal/Core/ParamConverter/EntityConverter.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\Core\ParamConverter;
 
+use Drupal\Core\Entity\EntityInterface;
 use Drupal\Core\Entity\EntityRepositoryInterface;
 use Drupal\Core\Entity\EntityTypeManagerInterface;
 use Drupal\Core\Plugin\Context\Context;
@@ -142,7 +143,11 @@ public function convert($value, $definition, $name, array $defaults) {
     }
     $entity = $this->entityRepository->getCanonical($entity_type_id, $value, $contexts);
 
-    if (!empty($definition['bundle']) && !in_array($entity->bundle(), $definition['bundle'], TRUE)) {
+    if (
+      !empty($definition['bundle']) &&
+      $entity instanceof EntityInterface &&
+      !in_array($entity->bundle(), $definition['bundle'], TRUE)
+    ) {
       return NULL;
     }
 
diff --git a/core/tests/Drupal/KernelTests/Core/ParamConverter/EntityConverterTest.php b/core/tests/Drupal/KernelTests/Core/ParamConverter/EntityConverterTest.php
index 2ad31fa97af0..9dfb943cd451 100644
--- a/core/tests/Drupal/KernelTests/Core/ParamConverter/EntityConverterTest.php
+++ b/core/tests/Drupal/KernelTests/Core/ParamConverter/EntityConverterTest.php
@@ -85,6 +85,10 @@ public function testRouteParamWithBundleDefinition(): void {
     $converted = $converter->convert($entity3->id(), $definition, 'qux', []);
     $this->assertNull($converted);
 
+    // A non-existing entity returns NULL.
+    $converted = $converter->convert('some-non-existing-entity-id', $definition, 'qux', []);
+    $this->assertNull($converted);
+
     $definition = [
       'type' => 'entity:entity_test',
     ];
@@ -96,6 +100,8 @@ public function testRouteParamWithBundleDefinition(): void {
     $this->assertSame($entity2->id(), $converted->id());
     $converted = $converter->convert($entity3->id(), $definition, 'qux', []);
     $this->assertSame($entity3->id(), $converted->id());
+    $converted = $converter->convert('some-non-existing-entity-id', $definition, 'qux', []);
+    $this->assertNull($converted);
   }
 
 }
-- 
GitLab