/
svgsprite.php
78 lines (73 loc) · 2.59 KB
/
svgsprite.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
/**
* @author Chris Zuber <shgysk8zer0@gmail.com>
* @package shgysk8zer0\DOM
* @version 0.0.1
* @since 0.0.1
* @copyright 2016, Chris Zuber
* @license https://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2 (GPL-2.0)
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
namespace shgysk8zer0\DOM;
use \shgysk8zer0\Core_API as API;
/**
* Class extending SVG for creating SVG Sprites.
*/
class SVGSprite extends SVG implements API\Interfaces\Magic_Methods, API\Interfaces\toString
{
/**
* Creates a new instance of SVGSprite
*
* @param Array $svgs Array of files to create from
*/
final public function __construct(Array $svgs)
{
parent::__construct();
array_map([$this, '_createSymbol'], array_values($svgs), array_keys($svgs));
}
/**
* Imports an SVG file as a new <symbol>
*
* @param string $file The name of the file to import from
* @return void
*/
final private function _createSymbol($file, $id)
{
if (! is_string($file)) {
throw new \InvalidArgumentException(sprintf(
'%s expects a string but got a %s',
__MEHTOD__,
gettype($file)
));
} else if (! file_exists($file)) {
throw new \Exception(sprintf('%s not found', $file), 1);
}
// Create a new SVG from the file
$svg = parent::loadSVG($file);
$symbol = $this->documentElement->appendChild($this->createElement('symbol'));
$symbol->id = is_string($id) ? $id : basename($file, '.svg');
// Attempt to set `viewBox` from either SVG's viewBox or dimensions
if (isset($svg->documentElement->viewBox)) {
$symbol->viewBox = $svg->documentElement->viewBox;
} else if (isset($svg->documentElement->width, $svg->documentElement->height)) {
$symbol->viewBox = "0 0 {$svg->documentElement->width} {$svg->documentElement->height}";
}
// Import and append SVG's childNodes
foreach ($svg->documentElement->childNodes as $node) {
$symbol->appendChild($this->importNode($node, true));
}
}
}