Skip to content

Commit

Permalink
Avoid duplicating assets when they have params
Browse files Browse the repository at this point in the history
  • Loading branch information
erikn69 committed Apr 7, 2022
1 parent 466603f commit b38fb29
Showing 1 changed file with 32 additions and 9 deletions.
41 changes: 32 additions & 9 deletions src/Assets.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class Assets
*/
public function __construct()
{
$this->collection = new Collection(['css' => array(), 'js' => array()]);
$this->collection = new Collection(['css' => [], 'js' => []]);
}

/**
Expand Down Expand Up @@ -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;
}
}

Expand Down Expand Up @@ -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.
*
Expand Down

0 comments on commit b38fb29

Please sign in to comment.