diff --git a/core/modules/file/src/Entity/File.php b/core/modules/file/src/Entity/File.php index 6417488..7bab1f9 100644 --- a/core/modules/file/src/Entity/File.php +++ b/core/modules/file/src/Entity/File.php @@ -277,4 +277,38 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { return $fields; } + /** + * Creates or reuses a file object based on a URI. + * + * @param string $uri + * A string containing the URI. + * @param bool $reuse_existing + * If TRUE will try to reuse an existing file with the same URI. + * If FALSE will always create a new file. + * + * @return static + * A file object. + */ + public static function createOrReuseFromUri($uri, $reuse_existing = TRUE) { + if ($reuse_existing) { + // Check if this file already exists, and if so, return that. + $storage = \Drupal::entityTypeManager()->getStorage('file'); + $files = $storage->loadByProperties(['uri' => $uri]); + if ($valid_files = array_filter($files, function (FileInterface $file) { + // By default only permanent files or temporary files owned by the + // current user should be re-used. + return $file->isPermanent() || $file->getOwnerId() == \Drupal::currentUser() + ->id(); + })) { + return reset($valid_files); + } + } + + // If an existing file could not be found, create a new file. + return static::create([ + 'uri' => $uri, + 'uid' => \Drupal::currentUser()->id(), + ]); + } + }