Skip to content

Instantly share code, notes, and snippets.

@dlundgren
Last active December 18, 2020 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dlundgren/89b50ed6c5d82f6792887459124e98d1 to your computer and use it in GitHub Desktop.
Save dlundgren/89b50ed6c5d82f6792887459124e98d1 to your computer and use it in GitHub Desktop.
<?php
namespace Assets;
use Assetic\Asset\AssetCollection;
use Assetic\Asset\AssetReference;
use Assetic\AssetManager;
class ResolveDependencies
{
/**
* @var AssetManager
*/
protected $manager;
public function process($payload)
{
$this->manager = $payload->manager;
foreach ($this->manager->getNames() as $name) {
$asset = $this->manager->get($name);
$this->seen = [];
if ($asset instanceof AssetCollection) {
list($seen, $remove) = $this->check($this->getReferenceNames($asset));
if (empty($remove)) {
continue;
}
foreach ($remove as $item) {
foreach ($asset->all() as $subAsset) {
if ($subAsset instanceof AssetReference && $subAsset->getName() === $item) {
$asset->removeLeaf($subAsset);
}
}
}
}
}
return $payload;
}
protected function check($refs, $seen = [], $remove = [])
{
foreach ($refs as $ref) {
if (!$this->manager->has($ref)) {
$remove[] = $ref;
continue;
}
$asset = $this->manager->get($ref);
if ($asset instanceof AssetCollection) {
list($s1, $r1) = $this->check($this->getReferenceNames($asset));
if ($tmp = array_intersect($refs, $s1)) {
$remove = array_merge($remove, $r1, $tmp);
}
}
$seen[] = $ref;
}
return [array_unique($seen), array_unique($remove)];
}
protected function getReferenceNames(AssetCollection $asset)
{
$assets = [];
foreach ($asset->all() as $subAsset) {
if ($subAsset instanceof AssetReference) {
$assets[] = $subAsset->getName();
}
}
return $assets;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment