Last active
December 18, 2020 18:02
-
-
Save dlundgren/89b50ed6c5d82f6792887459124e98d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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