Completed
Pull Request — master (#146)
by
unknown
14:28
created
Classes/Service/SvgStoreService.php 2 patches
Indentation   +252 added lines, -252 removed lines patch added patch discarded remove patch
@@ -13,256 +13,256 @@
 block discarded – undo
13 13
  */
14 14
 class SvgStoreService implements \TYPO3\CMS\Core\SingletonInterface
15 15
 {
16
-    /**
17
-     * SVG-Sprite relativ storage directory.
18
-     *
19
-     * @var string
20
-     */
21
-    protected $outputDir = '/typo3temp/assets/svg/';
22
-
23
-    /**
24
-     * TYPO3 absolute path to public web.
25
-     *
26
-     * @var string
27
-     */
28
-    protected $sitePath = '';
29
-
30
-    /**
31
-     * Final TYPO3 Frontend-Cache object.
32
-     *
33
-     * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
34
-     */
35
-    protected $svgCache;
36
-
37
-    /**
38
-     * Cached SVG-Sprite relativ file path.
39
-     *
40
-     * @var string
41
-     */
42
-    protected $spritePath = '';
43
-
44
-    /**
45
-     * Cached used SVG files (incl. defs).
46
-     *
47
-     * @var array
48
-     */
49
-    protected $svgFileArr = [];
50
-
51
-    /**
52
-     * Final SVG-Sprite Vectors.
53
-     *
54
-     * @var array
55
-     */
56
-    protected $svgs = [];
57
-
58
-    /**
59
-     * Final SVG-Sprite Styles.
60
-     *
61
-     * @var array
62
-     */
63
-    protected $styl = []; // ToFix ; https://stackoverflow.com/questions/39583880/external-svg-fails-to-apply-internal-css
64
-
65
-    /**
66
-     * Final SVG-Sprite Objects.
67
-     *
68
-     * @var array
69
-     */
70
-    protected $defs = []; // ToFix ; https://bugs.chromium.org/p/chromium/issues/detail?id=751733#c14
71
-
72
-    public function __construct()
73
-    {
74
-        $this->sitePath = \TYPO3\CMS\Core\Core\Environment::getPublicPath(); // [^/]$
75
-        $this->svgCache = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('svgstore');
76
-
77
-        $this->spritePath = $this->svgCache->get('spritePath') ?: '';
78
-        $this->svgFileArr = $this->svgCache->get('svgFileArr') ?: [];
79
-
80
-        if (empty($this->spritePath) && !$this->populateCache()) {
81
-            throw new \Exception('could not write file: '.$this->sitePath.$this->spritePath);
82
-        }
83
-
84
-        if (!file_exists($this->sitePath.$this->spritePath)) {
85
-            throw new \Exception('file does not exists: '.$this->sitePath.$this->spritePath);
86
-        }
87
-    }
88
-
89
-    public function process(string $html): string
90
-    {
91
-        if(empty($this->svgFileArr)) {
92
-            return $html;
93
-        }
94
-
95
-        if ($GLOBALS['TSFE']->config['config']['disableAllHeaderCode'] ?? false) {
96
-            $dom = ['head' => '', 'body' => $html];
97
-        } elseif (!preg_match('/(?<head>.+?<\/head>)(?<body>.+)/s', $html, $dom)) {
98
-            return $html;
99
-        }
100
-
101
-        // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attributes
102
-        $dom['body'] = preg_replace_callback('/<img(?<pre>[^>]*)src="(?:https?:)?(?:\/\/[^\/]+?)?(?<src>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?!\s*<\/picture>)/s', function (array $match): string { // ^[/]
103
-            if (!isset($this->svgFileArr[$match['src']])) { // check usage
104
-                return $match[0];
105
-            }
106
-            $attr = preg_replace('/\s(?:alt|ismap|loading|title|sizes|srcset|usemap|crossorigin|decoding|fetchpriority|referrerpolicy)="[^"]*"/', '', $match['pre'].$match['post']); // cleanup
107
-
108
-            return sprintf('<svg %s %s><use href="%s#%s"/></svg>', $this->svgFileArr[$match['src']]['attr'], trim($attr), $this->spritePath, $this->convertFilePath($match['src']));
109
-        }, $dom['body']);
110
-
111
-        // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#attributes
112
-        $dom['body'] = preg_replace_callback('/<object(?<pre>[^>]*)data="(?<data>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?:<\/object>)/s', function (array $match): string { // ^[/]
113
-            if (!isset($this->svgFileArr[$match['data']])) { // check usage
114
-                return $match[0];
115
-            }
116
-            $attr = preg_replace('/\s(?:form|name|type|usemap)="[^"]*"/', '', $match['pre'].$match['post']); // cleanup
117
-
118
-            return sprintf('<svg %s %s><use href="%s#%s"/></svg>', $this->svgFileArr[$match['data']]['attr'], trim($attr), $this->spritePath, $this->convertFilePath($match['data']));
119
-        }, $dom['body']);
120
-
121
-        return $dom['head'].$dom['body'];
122
-    }
123
-
124
-    private function convertFilePath(string $path): string
125
-    {
126
-        return preg_replace('/.svg$|[^\w\-]/', '', str_replace('/', '-', ltrim($path, '/'))); // ^[^/]
127
-    }
128
-
129
-    private function addFileToSpriteArr(string $hash, string $path, array $attr = []): ?array
130
-    {
131
-        if (!file_exists($this->sitePath.$path)) {
132
-            return null;
133
-        }
134
-
135
-        $svg = file_get_contents($this->sitePath.$path);
136
-
137
-        if (preg_match('/(?:;base64|i:a?i?pgf)/', $svg)) { // noop!
138
-            return null;
139
-        }
140
-
141
-        if (preg_match('/<(?:style|defs)|url\(/', $svg)) {
142
-            return null; // check links @ __construct
143
-        }
144
-
145
-        // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href
146
-        $svg = preg_replace('/^.*?<svg|\s*(<\/svg>)(?!.*\1).*$|xlink:|\s(?:(?:version|xmlns)|(?:[a-z\-]+\:[a-z\-]+))="[^"]*"/s', '', $svg); // cleanup
147
-
148
-        // $svg = preg_replace('/(?<=(?:id|class)=")/', $hash.'__', $svg); // extend  IDs
149
-        // $svg = preg_replace('/(?<=href="|url\()#/', $hash.'__', $svg); // recover IDs
150
-
151
-        // $svg = preg_replace_callback('/<style[^>]*>(?<styl>.+?)<\/style>|<defs[^>]*>(?<defs>.+?)<\/defs>/s', function(array $match) use($hash): string {
152
-        //
153
-        //    if(isset($match['styl']))
154
-        //    {
155
-        //        $this->styl[] = preg_replace('/\s*(\.|#){1}(.+?)\s*\{/', '$1'.$hash.'__$2{', $match['styl']); // patch CSS # https://mathiasbynens.be/notes/css-escapes
156
-        //    }
157
-        //    if(isset($match['defs']))
158
-        //    {
159
-        //        $this->defs[] = trim($match['defs']);
160
-        //    }
161
-        //    return '';
162
-        // }, $svg);
163
-
164
-        // https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg#attributes
165
-        $svg = preg_replace_callback('/([^>]*)\s*(?=>)/s', function (array $match) use (&$attr): string {
166
-            if (false === preg_match_all('/(?!\s)(?<attr>[a-z\-]+)="\s*(?<value>[^"]+)\s*"/i', $match[1], $matches)) {
167
-                return $match[0];
168
-            }
169
-            foreach ($matches['attr'] as $index => $attribute) {
170
-                switch ($attribute) {
171
-                    case 'id':
172
-                    case 'width':
173
-                    case 'height':
174
-                        unset($matches[0][$index]);
175
-                        break;
176
-
177
-                    case 'viewBox':
178
-                        if (false !== preg_match('/(?<minX>[-+]?[\d\.]+)\s(?<minY>[-+]?[\d\.]+)\s\+?(?<width>[\d\.]+)\s\+?(?<height>[\d\.]+)/', $matches['value'][$index], $match)) {
179
-                            $attr[] = sprintf('%s="%s %s %s %s"', $attribute, $match['minX'], $match['minY'], $match['width'], $match['height']); // save!
180
-                        }
181
-                }
182
-            }
183
-
184
-            return implode(' ', $matches[0]);
185
-        }, $svg, 1);
186
-
187
-        if (empty($attr)) {
188
-            return null;
189
-        }
190
-
191
-        $this->svgs[] = sprintf('id="%s" %s', $this->convertFilePath($path), $svg); // prepend ID
192
-
193
-        return ['attr' => implode(' ', $attr), 'hash' => $hash];
194
-    }
195
-
196
-    private function populateCache(): bool
197
-    {
198
-        $storageArr = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class)->findByStorageType('Local');
199
-        foreach ($storageArr as $storage) {
200
-            $storageConfig = $storage->getConfiguration();
201
-            if (!is_array($storageConfig) || !isset($storageConfig['pathType'], $storageConfig['basePath'])) {
202
-                continue;
203
-            }
204
-            if ('relative' == $storageConfig['pathType']) {
205
-                $storageArr[$storage->getUid()] = rtrim($storageConfig['basePath'], '/'); // [^/]$
206
-            }
207
-        }
208
-        unset($storageArr[0]); // keep!
209
-
210
-        $fileArr = GeneralUtility::makeInstance(\HTML\Sourceopt\Resource\SvgFileRepository::class)->findAllByStorageUids(array_keys($storageArr));
211
-        foreach ($fileArr as $file) {
212
-            $file['path'] = '/'.$storageArr[$file['storage']].$file['identifier']; // ^[/]
213
-            $file['defs'] = $this->addFileToSpriteArr($file['sha1'], $file['path']);
214
-
215
-            if (null !== $file['defs']) {
216
-                $this->svgFileArr[$file['path']] = $file['defs'];
217
-            }
218
-        }
219
-        unset($storageArr, $storage, $fileArr, $file); // save MEM
220
-
221
-        if(empty($this->svgFileArr)) {
222
-            return true;
223
-        }
224
-
225
-        $svg = preg_replace_callback(
226
-            '/<use(?<pre>.*?)(?:xlink:)?href="(?<href>\/.+?\.svg)(?:#[^"]*?)?"(?<post>.*?)[\s\/]*>(?:<\/use>)?/s',
227
-            function (array $match): string {
228
-                if (!isset($this->svgFileArr[$match['href']])) { // check usage
229
-                    return $match[0];
230
-                }
231
-
232
-                return sprintf('<use%s href="#%s"/>', $match['pre'].$match['post'], $this->convertFilePath($match['href']));
233
-            },
234
-            '<svg xmlns="http://www.w3.org/2000/svg">'
235
-            // ."\n<style>\n".implode("\n", $this->styl)."\n</style>"
236
-            // ."\n<defs>\n".implode("\n", $this->defs)."\n</defs>"
237
-            ."\n<symbol ".implode("</symbol>\n<symbol ", $this->svgs)."</symbol>\n"
238
-            .'</svg>'
239
-        );
240
-
241
-        // unset($this->styl); // save MEM
242
-        // unset($this->defs); // save MEM
243
-        unset($this->svgs); // save MEM
244
-
245
-        if ($GLOBALS['TSFE']->config['config']['sourceopt.']['formatHtml'] ?? false) {
246
-            $svg = preg_replace('/(?<=>)\s+(?=<)/', '', $svg); // remove emptiness
247
-            $svg = preg_replace('/[\t\v]/', ' ', $svg); // prepare shrinkage
248
-            $svg = preg_replace('/\s{2,}/', ' ', $svg); // shrink whitespace
249
-        }
250
-
251
-        $svg = preg_replace('/<([a-z\-]+)\s*(\/|>\s*<\/\1)>\s*|\s+(?=\/>)/i', '', $svg); // remove emtpy TAGs & shorten endings
252
-        $svg = preg_replace('/<((circle|ellipse|line|path|polygon|polyline|rect|stop|use)\s[^>]+?)\s*>\s*<\/\2>/', '<$1/>', $svg); // shorten/minify TAG syntax
253
-
254
-        if (!is_dir($this->sitePath.$this->outputDir)) {
255
-            GeneralUtility::mkdir_deep($this->sitePath.$this->outputDir);
256
-        }
257
-
258
-        $this->spritePath = $this->outputDir.hash('sha1', serialize($this->svgFileArr)).'.svg';
259
-        if (false === file_put_contents($this->sitePath.$this->spritePath, $svg)) {
260
-            return false;
261
-        }
262
-
263
-        $this->svgCache->set('spritePath', $this->spritePath);
264
-        $this->svgCache->set('svgFileArr', $this->svgFileArr);
265
-
266
-        return true;
267
-    }
16
+	/**
17
+	 * SVG-Sprite relativ storage directory.
18
+	 *
19
+	 * @var string
20
+	 */
21
+	protected $outputDir = '/typo3temp/assets/svg/';
22
+
23
+	/**
24
+	 * TYPO3 absolute path to public web.
25
+	 *
26
+	 * @var string
27
+	 */
28
+	protected $sitePath = '';
29
+
30
+	/**
31
+	 * Final TYPO3 Frontend-Cache object.
32
+	 *
33
+	 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
34
+	 */
35
+	protected $svgCache;
36
+
37
+	/**
38
+	 * Cached SVG-Sprite relativ file path.
39
+	 *
40
+	 * @var string
41
+	 */
42
+	protected $spritePath = '';
43
+
44
+	/**
45
+	 * Cached used SVG files (incl. defs).
46
+	 *
47
+	 * @var array
48
+	 */
49
+	protected $svgFileArr = [];
50
+
51
+	/**
52
+	 * Final SVG-Sprite Vectors.
53
+	 *
54
+	 * @var array
55
+	 */
56
+	protected $svgs = [];
57
+
58
+	/**
59
+	 * Final SVG-Sprite Styles.
60
+	 *
61
+	 * @var array
62
+	 */
63
+	protected $styl = []; // ToFix ; https://stackoverflow.com/questions/39583880/external-svg-fails-to-apply-internal-css
64
+
65
+	/**
66
+	 * Final SVG-Sprite Objects.
67
+	 *
68
+	 * @var array
69
+	 */
70
+	protected $defs = []; // ToFix ; https://bugs.chromium.org/p/chromium/issues/detail?id=751733#c14
71
+
72
+	public function __construct()
73
+	{
74
+		$this->sitePath = \TYPO3\CMS\Core\Core\Environment::getPublicPath(); // [^/]$
75
+		$this->svgCache = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('svgstore');
76
+
77
+		$this->spritePath = $this->svgCache->get('spritePath') ?: '';
78
+		$this->svgFileArr = $this->svgCache->get('svgFileArr') ?: [];
79
+
80
+		if (empty($this->spritePath) && !$this->populateCache()) {
81
+			throw new \Exception('could not write file: '.$this->sitePath.$this->spritePath);
82
+		}
83
+
84
+		if (!file_exists($this->sitePath.$this->spritePath)) {
85
+			throw new \Exception('file does not exists: '.$this->sitePath.$this->spritePath);
86
+		}
87
+	}
88
+
89
+	public function process(string $html): string
90
+	{
91
+		if(empty($this->svgFileArr)) {
92
+			return $html;
93
+		}
94
+
95
+		if ($GLOBALS['TSFE']->config['config']['disableAllHeaderCode'] ?? false) {
96
+			$dom = ['head' => '', 'body' => $html];
97
+		} elseif (!preg_match('/(?<head>.+?<\/head>)(?<body>.+)/s', $html, $dom)) {
98
+			return $html;
99
+		}
100
+
101
+		// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attributes
102
+		$dom['body'] = preg_replace_callback('/<img(?<pre>[^>]*)src="(?:https?:)?(?:\/\/[^\/]+?)?(?<src>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?!\s*<\/picture>)/s', function (array $match): string { // ^[/]
103
+			if (!isset($this->svgFileArr[$match['src']])) { // check usage
104
+				return $match[0];
105
+			}
106
+			$attr = preg_replace('/\s(?:alt|ismap|loading|title|sizes|srcset|usemap|crossorigin|decoding|fetchpriority|referrerpolicy)="[^"]*"/', '', $match['pre'].$match['post']); // cleanup
107
+
108
+			return sprintf('<svg %s %s><use href="%s#%s"/></svg>', $this->svgFileArr[$match['src']]['attr'], trim($attr), $this->spritePath, $this->convertFilePath($match['src']));
109
+		}, $dom['body']);
110
+
111
+		// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#attributes
112
+		$dom['body'] = preg_replace_callback('/<object(?<pre>[^>]*)data="(?<data>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?:<\/object>)/s', function (array $match): string { // ^[/]
113
+			if (!isset($this->svgFileArr[$match['data']])) { // check usage
114
+				return $match[0];
115
+			}
116
+			$attr = preg_replace('/\s(?:form|name|type|usemap)="[^"]*"/', '', $match['pre'].$match['post']); // cleanup
117
+
118
+			return sprintf('<svg %s %s><use href="%s#%s"/></svg>', $this->svgFileArr[$match['data']]['attr'], trim($attr), $this->spritePath, $this->convertFilePath($match['data']));
119
+		}, $dom['body']);
120
+
121
+		return $dom['head'].$dom['body'];
122
+	}
123
+
124
+	private function convertFilePath(string $path): string
125
+	{
126
+		return preg_replace('/.svg$|[^\w\-]/', '', str_replace('/', '-', ltrim($path, '/'))); // ^[^/]
127
+	}
128
+
129
+	private function addFileToSpriteArr(string $hash, string $path, array $attr = []): ?array
130
+	{
131
+		if (!file_exists($this->sitePath.$path)) {
132
+			return null;
133
+		}
134
+
135
+		$svg = file_get_contents($this->sitePath.$path);
136
+
137
+		if (preg_match('/(?:;base64|i:a?i?pgf)/', $svg)) { // noop!
138
+			return null;
139
+		}
140
+
141
+		if (preg_match('/<(?:style|defs)|url\(/', $svg)) {
142
+			return null; // check links @ __construct
143
+		}
144
+
145
+		// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href
146
+		$svg = preg_replace('/^.*?<svg|\s*(<\/svg>)(?!.*\1).*$|xlink:|\s(?:(?:version|xmlns)|(?:[a-z\-]+\:[a-z\-]+))="[^"]*"/s', '', $svg); // cleanup
147
+
148
+		// $svg = preg_replace('/(?<=(?:id|class)=")/', $hash.'__', $svg); // extend  IDs
149
+		// $svg = preg_replace('/(?<=href="|url\()#/', $hash.'__', $svg); // recover IDs
150
+
151
+		// $svg = preg_replace_callback('/<style[^>]*>(?<styl>.+?)<\/style>|<defs[^>]*>(?<defs>.+?)<\/defs>/s', function(array $match) use($hash): string {
152
+		//
153
+		//    if(isset($match['styl']))
154
+		//    {
155
+		//        $this->styl[] = preg_replace('/\s*(\.|#){1}(.+?)\s*\{/', '$1'.$hash.'__$2{', $match['styl']); // patch CSS # https://mathiasbynens.be/notes/css-escapes
156
+		//    }
157
+		//    if(isset($match['defs']))
158
+		//    {
159
+		//        $this->defs[] = trim($match['defs']);
160
+		//    }
161
+		//    return '';
162
+		// }, $svg);
163
+
164
+		// https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg#attributes
165
+		$svg = preg_replace_callback('/([^>]*)\s*(?=>)/s', function (array $match) use (&$attr): string {
166
+			if (false === preg_match_all('/(?!\s)(?<attr>[a-z\-]+)="\s*(?<value>[^"]+)\s*"/i', $match[1], $matches)) {
167
+				return $match[0];
168
+			}
169
+			foreach ($matches['attr'] as $index => $attribute) {
170
+				switch ($attribute) {
171
+					case 'id':
172
+					case 'width':
173
+					case 'height':
174
+						unset($matches[0][$index]);
175
+						break;
176
+
177
+					case 'viewBox':
178
+						if (false !== preg_match('/(?<minX>[-+]?[\d\.]+)\s(?<minY>[-+]?[\d\.]+)\s\+?(?<width>[\d\.]+)\s\+?(?<height>[\d\.]+)/', $matches['value'][$index], $match)) {
179
+							$attr[] = sprintf('%s="%s %s %s %s"', $attribute, $match['minX'], $match['minY'], $match['width'], $match['height']); // save!
180
+						}
181
+				}
182
+			}
183
+
184
+			return implode(' ', $matches[0]);
185
+		}, $svg, 1);
186
+
187
+		if (empty($attr)) {
188
+			return null;
189
+		}
190
+
191
+		$this->svgs[] = sprintf('id="%s" %s', $this->convertFilePath($path), $svg); // prepend ID
192
+
193
+		return ['attr' => implode(' ', $attr), 'hash' => $hash];
194
+	}
195
+
196
+	private function populateCache(): bool
197
+	{
198
+		$storageArr = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class)->findByStorageType('Local');
199
+		foreach ($storageArr as $storage) {
200
+			$storageConfig = $storage->getConfiguration();
201
+			if (!is_array($storageConfig) || !isset($storageConfig['pathType'], $storageConfig['basePath'])) {
202
+				continue;
203
+			}
204
+			if ('relative' == $storageConfig['pathType']) {
205
+				$storageArr[$storage->getUid()] = rtrim($storageConfig['basePath'], '/'); // [^/]$
206
+			}
207
+		}
208
+		unset($storageArr[0]); // keep!
209
+
210
+		$fileArr = GeneralUtility::makeInstance(\HTML\Sourceopt\Resource\SvgFileRepository::class)->findAllByStorageUids(array_keys($storageArr));
211
+		foreach ($fileArr as $file) {
212
+			$file['path'] = '/'.$storageArr[$file['storage']].$file['identifier']; // ^[/]
213
+			$file['defs'] = $this->addFileToSpriteArr($file['sha1'], $file['path']);
214
+
215
+			if (null !== $file['defs']) {
216
+				$this->svgFileArr[$file['path']] = $file['defs'];
217
+			}
218
+		}
219
+		unset($storageArr, $storage, $fileArr, $file); // save MEM
220
+
221
+		if(empty($this->svgFileArr)) {
222
+			return true;
223
+		}
224
+
225
+		$svg = preg_replace_callback(
226
+			'/<use(?<pre>.*?)(?:xlink:)?href="(?<href>\/.+?\.svg)(?:#[^"]*?)?"(?<post>.*?)[\s\/]*>(?:<\/use>)?/s',
227
+			function (array $match): string {
228
+				if (!isset($this->svgFileArr[$match['href']])) { // check usage
229
+					return $match[0];
230
+				}
231
+
232
+				return sprintf('<use%s href="#%s"/>', $match['pre'].$match['post'], $this->convertFilePath($match['href']));
233
+			},
234
+			'<svg xmlns="http://www.w3.org/2000/svg">'
235
+			// ."\n<style>\n".implode("\n", $this->styl)."\n</style>"
236
+			// ."\n<defs>\n".implode("\n", $this->defs)."\n</defs>"
237
+			."\n<symbol ".implode("</symbol>\n<symbol ", $this->svgs)."</symbol>\n"
238
+			.'</svg>'
239
+		);
240
+
241
+		// unset($this->styl); // save MEM
242
+		// unset($this->defs); // save MEM
243
+		unset($this->svgs); // save MEM
244
+
245
+		if ($GLOBALS['TSFE']->config['config']['sourceopt.']['formatHtml'] ?? false) {
246
+			$svg = preg_replace('/(?<=>)\s+(?=<)/', '', $svg); // remove emptiness
247
+			$svg = preg_replace('/[\t\v]/', ' ', $svg); // prepare shrinkage
248
+			$svg = preg_replace('/\s{2,}/', ' ', $svg); // shrink whitespace
249
+		}
250
+
251
+		$svg = preg_replace('/<([a-z\-]+)\s*(\/|>\s*<\/\1)>\s*|\s+(?=\/>)/i', '', $svg); // remove emtpy TAGs & shorten endings
252
+		$svg = preg_replace('/<((circle|ellipse|line|path|polygon|polyline|rect|stop|use)\s[^>]+?)\s*>\s*<\/\2>/', '<$1/>', $svg); // shorten/minify TAG syntax
253
+
254
+		if (!is_dir($this->sitePath.$this->outputDir)) {
255
+			GeneralUtility::mkdir_deep($this->sitePath.$this->outputDir);
256
+		}
257
+
258
+		$this->spritePath = $this->outputDir.hash('sha1', serialize($this->svgFileArr)).'.svg';
259
+		if (false === file_put_contents($this->sitePath.$this->spritePath, $svg)) {
260
+			return false;
261
+		}
262
+
263
+		$this->svgCache->set('spritePath', $this->spritePath);
264
+		$this->svgCache->set('svgFileArr', $this->svgFileArr);
265
+
266
+		return true;
267
+	}
268 268
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
 
89 89
     public function process(string $html): string
90 90
     {
91
-        if(empty($this->svgFileArr)) {
91
+        if (empty($this->svgFileArr)) {
92 92
             return $html;
93 93
         }
94 94
 
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
         }
100 100
 
101 101
         // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attributes
102
-        $dom['body'] = preg_replace_callback('/<img(?<pre>[^>]*)src="(?:https?:)?(?:\/\/[^\/]+?)?(?<src>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?!\s*<\/picture>)/s', function (array $match): string { // ^[/]
102
+        $dom['body'] = preg_replace_callback('/<img(?<pre>[^>]*)src="(?:https?:)?(?:\/\/[^\/]+?)?(?<src>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?!\s*<\/picture>)/s', function(array $match): string { // ^[/]
103 103
             if (!isset($this->svgFileArr[$match['src']])) { // check usage
104 104
                 return $match[0];
105 105
             }
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
         }, $dom['body']);
110 110
 
111 111
         // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#attributes
112
-        $dom['body'] = preg_replace_callback('/<object(?<pre>[^>]*)data="(?<data>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?:<\/object>)/s', function (array $match): string { // ^[/]
112
+        $dom['body'] = preg_replace_callback('/<object(?<pre>[^>]*)data="(?<data>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?:<\/object>)/s', function(array $match): string { // ^[/]
113 113
             if (!isset($this->svgFileArr[$match['data']])) { // check usage
114 114
                 return $match[0];
115 115
             }
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
         // }, $svg);
163 163
 
164 164
         // https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg#attributes
165
-        $svg = preg_replace_callback('/([^>]*)\s*(?=>)/s', function (array $match) use (&$attr): string {
165
+        $svg = preg_replace_callback('/([^>]*)\s*(?=>)/s', function(array $match) use (&$attr): string {
166 166
             if (false === preg_match_all('/(?!\s)(?<attr>[a-z\-]+)="\s*(?<value>[^"]+)\s*"/i', $match[1], $matches)) {
167 167
                 return $match[0];
168 168
             }
@@ -218,13 +218,13 @@  discard block
 block discarded – undo
218 218
         }
219 219
         unset($storageArr, $storage, $fileArr, $file); // save MEM
220 220
 
221
-        if(empty($this->svgFileArr)) {
221
+        if (empty($this->svgFileArr)) {
222 222
             return true;
223 223
         }
224 224
 
225 225
         $svg = preg_replace_callback(
226 226
             '/<use(?<pre>.*?)(?:xlink:)?href="(?<href>\/.+?\.svg)(?:#[^"]*?)?"(?<post>.*?)[\s\/]*>(?:<\/use>)?/s',
227
-            function (array $match): string {
227
+            function(array $match): string {
228 228
                 if (!isset($this->svgFileArr[$match['href']])) { // check usage
229 229
                     return $match[0];
230 230
                 }
Please login to merge, or discard this patch.