diff options
Diffstat (limited to 'src/SvgSpriteCompiler.php')
| -rw-r--r-- | src/SvgSpriteCompiler.php | 85 | 
1 files changed, 85 insertions, 0 deletions
| diff --git a/src/SvgSpriteCompiler.php b/src/SvgSpriteCompiler.php new file mode 100644 index 0000000..b4ed89f --- /dev/null +++ b/src/SvgSpriteCompiler.php @@ -0,0 +1,85 @@ +<?php + +namespace Lightscale\LaralightSvg; + +use DOMDocument; +use DOMNode; +use DOMElement; + +class SvgSpriteCompiler +{ +    protected bool $isNew = false; + +    private DOMDocument $svg; +    private DOMNode $defs; + +    public function __construct(string $svg) +    { +        $svg = empty($svg) ? $this->newSvg() : $svg; +; +        if (!$this->loadSvg($svg)) { +            $this->loadSvg($this->newSvg()); +        } + +        $this->defs = $this->svg->getElementsByTagName('defs')[0]; + +    } + +    protected function loadSvg(string $svg): bool +    { +        $this->svg = new DOMDocument(); +        return $this->svg->loadXML($svg, LIBXML_NOXMLDECL); +    } + +    protected function newSvg(): string +    { +        $this->isNew = true; +        return '<svg xmlns="http://www.w3.org/2000/svg"><defs></defs></svg>'; +    } + +    public function isNew(): bool +    { +        return $this->isNew; +    } + +    public function getSvg(): string +    { +        return $this->svg->saveXML(null, LIBXML_NOXMLDECL); +    } + +    public function addSvg(string $name, string $svg): bool +    { +        $doc = new DOMDocument; +        if (!$doc->loadXML($svg)) return false; + +        $svg = $doc->getElementsByTagName('svg')->item(0); +        if ($svg instanceof DOMElement) { +            $this->defs->appendChild($this->createSymbol($name, $svg)); +            return true; +        } +        else { +            return false; +        } +    } + +    private function createSymbol(string $name, DOMElement $svg): DOMElement +    { +        $attributes = ['width', 'height', 'x', 'y', 'viewBox', 'preserveAspectRatio']; +        $symbol = $this->svg->createElement('symbol'); + +        $symbol->setAttribute('id', $name); +        foreach ($attributes as $attr) { +            if ($svg->hasAttribute($attr)) { +                $value = $svg->getAttribute($attr); +                $symbol->setAttribute($attr, $value); +            } +        } + +        foreach ($svg->childNodes as $node) { +            $symbol->appendChild($this->svg->importNode($node, true)); +        } + +        return $symbol; +    } + +} | 
