From 81e6c3467bdc5508021ca7c77d4fac06f8f2834c Mon Sep 17 00:00:00 2001
From: Sam Light <samlight1994@gmail.com>
Date: Sat, 15 Jun 2024 23:01:51 +0100
Subject: Created SvgSpriteCompiler

---
 src/SvgSpriteCompiler.php | 85 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 85 insertions(+)
 create mode 100644 src/SvgSpriteCompiler.php

(limited to 'src')

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;
+    }
+
+}
-- 
cgit v1.2.3