From b38fb299a01a78b8e77a6f3d6bc9e5572816ef2b Mon Sep 17 00:00:00 2001 From: erikn69 Date: Tue, 8 Mar 2022 14:00:50 -0500 Subject: [PATCH] Avoid duplicating assets when they have params --- src/Assets.php | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/src/Assets.php b/src/Assets.php index 9e8af27..ecb053d 100644 --- a/src/Assets.php +++ b/src/Assets.php @@ -29,7 +29,7 @@ class Assets */ public function __construct() { - $this->collection = new Collection(['css' => array(), 'js' => array()]); + $this->collection = new Collection(['css' => [], 'js' => []]); } /** @@ -62,13 +62,13 @@ public function dependsOn($dependency) $collection = $this->collection->get($this->lastAddedType); foreach ($collection as $path => $item) { - if ($path === $this->lastAddedAsset) { - $collection[$path] = array( - 'namespace' => $item['namespace'], + if (self::cleanAsset($path) === $this->lastAddedAsset) { + $collection[$path] = array_merge($item, [ 'dependency' => $dependency - ); + ]); $this->collection->put($this->lastAddedType, $collection); + break; } } @@ -171,22 +171,45 @@ protected function addAsset($assets, $namespace = null) $type = ($this->isCss($assets)) ? 'css' : 'js'; $collection = $this->collection->get($type); + $cleanAsset = self::cleanAsset($assets); + $existingAssets = array_map(function ($asset) { + return self::cleanAsset($asset); + }, array_keys($collection)); - if (! in_array($assets, $collection)) { + if (! in_array($cleanAsset, $existingAssets)) { $collection[$assets] = array( 'namespace' => $namespace, 'dependency' => array() ); $this->collection->put($type, $collection); - - $this->lastAddedType = $type; - $this->lastAddedAsset = $assets; } + $this->lastAddedType = $type; + $this->lastAddedAsset = $cleanAsset; + return $this; } + /** + * Remove `?` anf `#` parts from asset + * + * @param string $asset + * @return string + */ + private static function cleanAsset($asset) + { + $asset = (string) $asset; + + $result = strstr($asset, '?', true); + $asset = $result === false ? $asset : $result; + + $result = strstr($asset, '#', true); + $asset = $result === false ? $asset : $result; + + return $asset; + } + /** * Parse a bonsai.json file and add the assets to the collection. *