summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorSam Light <samlight1994@gmail.com>2024-06-15 23:01:51 +0100
committerSam Light <samlight1994@gmail.com>2024-06-15 23:01:51 +0100
commit81e6c3467bdc5508021ca7c77d4fac06f8f2834c (patch)
tree56fa6f563460145fb8fcb48445f0cc7e92850dc8 /src
parent9f31ec18ba36839ef8b6c87b6a409c40145cff72 (diff)
Created SvgSpriteCompiler
Diffstat (limited to 'src')
-rw-r--r--src/SvgSpriteCompiler.php85
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;
+ }
+
+}