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