From de16214a46574fd71420753490e6db1a966124d3 Mon Sep 17 00:00:00 2001
From: Merlin <merlin@geeks4change.net>
Date: Thu, 26 Mar 2020 00:18:49 +0100
Subject: [PATCH] Robustified AssetInjectorBase::filePathRelativeToDrupalRoot,
 which might fix #3089358

---
 src/Entity/AssetInjectorBase.php | 38 ++++++++++++++++++++++++++++----
 1 file changed, 34 insertions(+), 4 deletions(-)

diff --git a/src/Entity/AssetInjectorBase.php b/src/Entity/AssetInjectorBase.php
index 72a74dc..db9bc2f 100644
--- a/src/Entity/AssetInjectorBase.php
+++ b/src/Entity/AssetInjectorBase.php
@@ -8,6 +8,7 @@ use Drupal\Core\Config\Entity\ConfigEntityBase;
 use Drupal\Core\Entity\EntityStorageInterface;
 use Drupal\Core\Entity\EntityWithPluginCollectionInterface;
 use Drupal\Core\Condition\ConditionPluginCollection;
+use Drupal\Core\StreamWrapper\LocalStream;
 
 /**
  * Class AssetInjectorBase: Base asset injector class.
@@ -72,6 +73,13 @@ abstract class AssetInjectorBase extends ConfigEntityBase implements AssetInject
    */
   protected $conditionPluginManager;
 
+  /**
+   * The stream wrapper manager.
+   *
+   * @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface
+   */
+  private $streamWrapperManager;
+
   /**
    * {@inheritdoc}
    */
@@ -101,14 +109,24 @@ abstract class AssetInjectorBase extends ConfigEntityBase implements AssetInject
   /**
    * Get file path relative to drupal root to use in library info.
    *
+   * For now, we have to local stream wrappers this to a path relative to Drupal
+   * root, until https://www.drupal.org/project/drupal/issues/2735717 is fixed.
+   *
    * @return string
    *   File path relative to drupal root, with leading slash.
    */
   protected function filePathRelativeToDrupalRoot() {
-    // @todo See if we can simplify this via file_url_transform_relative().
-    $path = parse_url(file_create_url($this->internalFileUri()), PHP_URL_PATH);
-    $path = str_replace(base_path(), '/', $path);
-    return $path;
+    $fileUri = $this->internalFileUri();
+    $wrapper = $this->getStreamWrapperManager()->getViaUri($fileUri);
+    if ($wrapper instanceof LocalStream) {
+      $publicPath = $wrapper->getDirectoryPath();
+      $targetPath = $this->streamWrapperManager->getTarget($fileUri);
+      $localPath = "/$publicPath/$targetPath";
+      return $localPath;
+    }
+    else {
+      return $fileUri;
+    }
   }
 
   /**
@@ -209,4 +227,16 @@ abstract class AssetInjectorBase extends ConfigEntityBase implements AssetInject
     return $this->conditionPluginManager;
   }
 
+  /**
+   * Gets the stream wrapper manager.
+   *
+   * @return \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface
+   */
+  public function getStreamWrapperManager() {
+    if (!isset($this->streamWrapperManager)) {
+      $this->streamWrapperManager = \Drupal::service('stream_wrapper_manager');
+    }
+    return $this->streamWrapperManager;
+  }
+
 }
-- 
2.17.1

