From 8ae898a87f376543ce6b1e50db7438cd559e0327 Mon Sep 17 00:00:00 2001
From: Alex Pott <alex.a.pott@googlemail.com>
Date: Sun, 8 May 2016 14:21:46 -0500
Subject: [PATCH] Issue #2660528 by swentel, david_garcia: File entity
 completely broken if the underlying file is gone

---
 core/modules/file/src/Entity/File.php         |  6 ++++-
 .../src/Tests/FileManagedFileElementTest.php  | 23 +++++++++++++++++++
 2 files changed, 28 insertions(+), 1 deletion(-)

diff --git a/core/modules/file/src/Entity/File.php b/core/modules/file/src/Entity/File.php
index 0c34871f51d8..6fd0cc758ae8 100644
--- a/core/modules/file/src/Entity/File.php
+++ b/core/modules/file/src/Entity/File.php
@@ -186,7 +186,11 @@ public static function preCreate(EntityStorageInterface $storage, array &$values
   public function preSave(EntityStorageInterface $storage) {
     parent::preSave($storage);
 
-    $this->setSize(filesize($this->getFileUri()));
+    // The file itself might not exist or be available right now.
+    $uri = $this->getFileUri();
+    if ($size = @filesize($uri)) {
+      $this->setSize($size);
+    }
   }
 
   /**
diff --git a/core/modules/file/src/Tests/FileManagedFileElementTest.php b/core/modules/file/src/Tests/FileManagedFileElementTest.php
index f5d5be39489d..07102a04df96 100644
--- a/core/modules/file/src/Tests/FileManagedFileElementTest.php
+++ b/core/modules/file/src/Tests/FileManagedFileElementTest.php
@@ -171,4 +171,27 @@ public function testManagedFileRemoved() {
     $this->assertRaw('The file referenced by the Managed <em>file &amp; butter</em> field does not exist.');
   }
 
+  /**
+   * Ensure a file entity can be saved when the file does not exist on disk.
+   */
+  public function testFileRemovedFromDisk() {
+    $this->drupalGet('file/test/1/0/1');
+    $test_file = $this->getTestFile('text');
+    $file_field_name = 'files[nested_file][]';
+
+    $edit = [$file_field_name => drupal_realpath($test_file->getFileUri())];
+    $this->drupalPostForm(NULL, $edit, t('Upload'));
+    $this->drupalPostForm(NULL, array(), t('Save'));
+
+    $fid = $this->getLastFileId();
+    /** @var $file \Drupal\file\FileInterface */
+    $file = $this->container->get('entity_type.manager')->getStorage('file')->load($fid);
+    $file->setPermanent();
+    $file->save();
+    $this->assertTrue(file_unmanaged_delete($file->getFileUri()));
+    $file->save();
+    $this->assertTrue($file->isPermanent());
+    $file->delete();
+  }
+
 }
-- 
GitLab