diff --git a/core/modules/image/src/Plugin/Field/FieldType/ImageItem.php b/core/modules/image/src/Plugin/Field/FieldType/ImageItem.php index c83e143..ce94894 100644 --- a/core/modules/image/src/Plugin/Field/FieldType/ImageItem.php +++ b/core/modules/image/src/Plugin/Field/FieldType/ImageItem.php @@ -9,6 +9,7 @@ use Drupal\Core\StreamWrapper\StreamWrapperInterface; use Drupal\Core\TypedData\DataDefinition; use Drupal\file\Entity\File; +use Drupal\file\FileInterface; use Drupal\file\Plugin\Field\FieldType\FileItem; /** @@ -313,13 +314,18 @@ public function preSave() { $height = $this->height; // Determine the dimensions if necessary. - if (empty($width) || empty($height)) { - $image = \Drupal::service('image.factory')->get($this->entity->getFileUri()); - if ($image->isValid()) { - $this->width = $image->getWidth(); - $this->height = $image->getHeight(); + if (($this->entity instanceof FileInterface)) { + if (empty($width) || empty($height)) { + $image = \Drupal::service('image.factory')->get($this->entity->getFileUri()); + if ($image->isValid()) { + $this->width = $image->getWidth(); + $this->height = $image->getHeight(); + } } } + else { + trigger_error(sprintf("A malformed file was provided. Cannot determine its dimensions."), E_USER_WARNING); + } } /** diff --git a/core/modules/image/tests/src/Kernel/ImageItemTest.php b/core/modules/image/tests/src/Kernel/ImageItemTest.php index dea4534..0c6fcfa 100644 --- a/core/modules/image/tests/src/Kernel/ImageItemTest.php +++ b/core/modules/image/tests/src/Kernel/ImageItemTest.php @@ -2,6 +2,7 @@ namespace Drupal\Tests\image\Kernel; +use Drupal\Core\Entity\EntityStorageException; use Drupal\Core\Field\FieldItemInterface; use Drupal\Core\Field\FieldItemListInterface; use Drupal\Core\Field\FieldStorageDefinitionInterface; @@ -108,6 +109,15 @@ public function testImageItem() { $this->assertEqual($entity->image_test->height, $image->getHeight()); $this->assertEqual($entity->image_test->alt, $new_alt); + // Validate entity is a file and don't gather dimensions if it is not. + $entity->image_test = NULL; + $entity->image_test->target_id = 0; + $this->setExpectedException(EntityStorageException::class, "A malformed file was provided. Cannot determine its dimensions."); + $entity->save(); + + $this->assertEmpty($entity->image_test->width); + $this->assertEmpty($entity->image_test->height); + // Check that the image item can be set to the referenced file directly. $entity->image_test = $this->image; $this->assertEqual($entity->image_test->target_id, $this->image->id());