Completed
Push — master ( 590855...8b87ed )
by Tim
21s queued 12s
created
Classes/Service/SvgStoreService.php 1 patch
Indentation   +185 added lines, -185 removed lines patch added patch discarded remove patch
@@ -13,190 +13,190 @@
 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 (!preg_match('/(?<head>.+?<\/head>)(?<body>.+)/s', $html, $html) && 5 == \count($html)) {
47
-            throw new \Exception('fix HTML!');
48
-        }
49
-
50
-        // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attributes
51
-        $html['body'] = preg_replace_callback('/<img(?<pre>[^>]*)src="(?<src>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?!\s*<\/picture>)/s', function (array $match): string { // ^[/]
52
-            if (!isset($this->svgFileArr[$match['src']])) { // check usage
53
-                return $match[0];
54
-            }
55
-            $attr = preg_replace('/\s(?:alt|ismap|loading|title|sizes|srcset|usemap|crossorigin|decoding|referrerpolicy)="[^"]*"/', '', $match['pre'].$match['post']); // cleanup
56
-
57
-            return sprintf('<svg %s %s><use href="%s#%s"/></svg>', $this->svgFileArr[$match['src']]['attr'], trim($attr), $this->spritePath, $this->convertFilePath($match['src']));
58
-        }, $html['body']);
59
-
60
-        // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#attributes
61
-        $html['body'] = preg_replace_callback('/<object(?<pre>[^>]*)data="(?<data>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?:<\/object>)/s', function (array $match): string { // ^[/]
62
-            if (!isset($this->svgFileArr[$match['data']])) { // check usage
63
-                return $match[0];
64
-            }
65
-            $attr = preg_replace('/\s(?:form|name|type|usemap)="[^"]*"/', '', $match['pre'].$match['post']); // cleanup
66
-
67
-            return sprintf('<svg %s %s><use href="%s#%s"/></svg>', $this->svgFileArr[$match['data']]['attr'], trim($attr), $this->spritePath, $this->convertFilePath($match['data']));
68
-        }, $html['body']);
69
-
70
-        return $html['head'].$html['body'];
71
-    }
72
-
73
-    private function convertFilePath(string $path): string
74
-    {
75
-        return preg_replace('/.svg$|[^\w\-]/', '', str_replace('/', '-', ltrim($path, '/'))); // ^[^/]
76
-    }
77
-
78
-    private function addFileToSpriteArr(string $hash, string $path): ?array
79
-    {
80
-        if (!file_exists($this->sitePath.$path)) {
81
-            return null;
82
-        }
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 (!preg_match('/(?<head>.+?<\/head>)(?<body>.+)/s', $html, $html) && 5 == \count($html)) {
47
+			throw new \Exception('fix HTML!');
48
+		}
49
+
50
+		// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attributes
51
+		$html['body'] = preg_replace_callback('/<img(?<pre>[^>]*)src="(?<src>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?!\s*<\/picture>)/s', function (array $match): string { // ^[/]
52
+			if (!isset($this->svgFileArr[$match['src']])) { // check usage
53
+				return $match[0];
54
+			}
55
+			$attr = preg_replace('/\s(?:alt|ismap|loading|title|sizes|srcset|usemap|crossorigin|decoding|referrerpolicy)="[^"]*"/', '', $match['pre'].$match['post']); // cleanup
56
+
57
+			return sprintf('<svg %s %s><use href="%s#%s"/></svg>', $this->svgFileArr[$match['src']]['attr'], trim($attr), $this->spritePath, $this->convertFilePath($match['src']));
58
+		}, $html['body']);
59
+
60
+		// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#attributes
61
+		$html['body'] = preg_replace_callback('/<object(?<pre>[^>]*)data="(?<data>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?:<\/object>)/s', function (array $match): string { // ^[/]
62
+			if (!isset($this->svgFileArr[$match['data']])) { // check usage
63
+				return $match[0];
64
+			}
65
+			$attr = preg_replace('/\s(?:form|name|type|usemap)="[^"]*"/', '', $match['pre'].$match['post']); // cleanup
66
+
67
+			return sprintf('<svg %s %s><use href="%s#%s"/></svg>', $this->svgFileArr[$match['data']]['attr'], trim($attr), $this->spritePath, $this->convertFilePath($match['data']));
68
+		}, $html['body']);
69
+
70
+		return $html['head'].$html['body'];
71
+	}
72
+
73
+	private function convertFilePath(string $path): string
74
+	{
75
+		return preg_replace('/.svg$|[^\w\-]/', '', str_replace('/', '-', ltrim($path, '/'))); // ^[^/]
76
+	}
77
+
78
+	private function addFileToSpriteArr(string $hash, string $path): ?array
79
+	{
80
+		if (!file_exists($this->sitePath.$path)) {
81
+			return null;
82
+		}
83 83
         
84
-        if (1 === preg_match('/(?:;base64|i:a?i?pgf)/', $svg = file_get_contents($this->sitePath.$path))) { // noop!
85
-            return null;
86
-        }
87
-
88
-        if (1 === preg_match('/<(?:style|defs)|url\(/', $svg)) {
89
-            return null; // check links @ __construct
90
-        }
91
-
92
-        //$svg = preg_replace('/((?:id|class)=")/', '$1'.$hash.'__', $svg); // extend  IDs
93
-        //$svg = preg_replace('/(href="|url\()#/', '$1#'.$hash.'__', $svg); // recover IDs
94
-
95
-        //$svg = preg_replace_callback('/<style[^>]*>(?<styl>.+?)<\/style>|<defs[^>]*>(?<defs>.+?)<\/defs>/s', function(array $match) use($hash): string {
96
-        //
97
-        //    if(isset($match['styl']))
98
-        //    {
99
-        //        $this->styl[] = preg_replace('/\s*(\.|#){1}(.+?)\s*\{/', '$1'.$hash.'__$2{', $match['styl']); // patch CSS # https://mathiasbynens.be/notes/css-escapes
100
-        //    }
101
-        //    if(isset($match['defs']))
102
-        //    {
103
-        //        $this->defs[] = trim($match['defs']);
104
-        //    }
105
-        //    return '';
106
-        //}, $svg);
107
-
108
-        // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href
109
-        $svg = preg_replace('/^.*?<svg|\s*(<\/svg>)(?!.*\1).*$|xlink:|\s(?:(?:version|xmlns)|(?:[a-z\-]+\:[a-z\-]+))="[^"]*"/s', '', $svg); // cleanup
110
-
111
-        // https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg#attributes
112
-        $svg = preg_replace_callback('/([^>]*)\s*(?=>)/s', function (array $match) use (&$attr): string {
113
-            if (false === preg_match_all('/(?!\s)(?<attr>[\w\-]+)="\s*(?<value>[^"]+)\s*"/', $match[1], $matches)) {
114
-                return $match[0];
115
-            }
116
-            foreach ($matches['attr'] as $index => $attribute) {
117
-                switch ($attribute) {
118
-                  case 'id':
119
-                  case 'width':
120
-                  case 'height':
121
-                      unset($matches[0][$index]);
122
-                      break;
123
-
124
-                  case 'viewBox':
125
-                      if (false !== preg_match('/\S+\s\S+\s\+?(?<width>[\d\.]+)\s\+?(?<height>[\d\.]+)/', $matches['value'][$index], $match)) {
126
-                          $attr[] = sprintf('%s="0 0 %s %s"', $attribute, $match['width'], $match['height']); // save!
127
-                      }
128
-                }
129
-            }
130
-
131
-            return implode(' ', $matches[0]);
132
-        }, $svg, 1);
133
-
134
-        if ($attr) { // TODO; beautify
135
-            $this->svgs[] = sprintf('id="%s" %s', $this->convertFilePath($path), $svg); // prepend ID
136
-
137
-            return ['attr' => implode(' ', $attr), 'hash' => $hash];
138
-        }
139
-
140
-        return null;
141
-    }
142
-
143
-    private function populateCache(): bool
144
-    {
145
-        $storageArr = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class)->findAll();
146
-        foreach ($storageArr as $storage) {
147
-            if ('relative' == $storage->getConfiguration()['pathType']) {
148
-                $storageArr[$storage->getUid()] = rtrim($storage->getConfiguration()['basePath'], '/'); // [^/]$
149
-            }
150
-        }
151
-        unset($storageArr[0]); // keep!
152
-
153
-        $svgFileArr = GeneralUtility::makeInstance(\HTML\Sourceopt\Resource\SvgFileRepository::class)->findAllByStorageUids(\array_keys($storageArr));
154
-        foreach ($svgFileArr as $index => $row) {
155
-            if (!$this->svgFileArr[($row['path'] = '/'.$storageArr[$row['storage']].$row['identifier'])] = $this->addFileToSpriteArr($row['sha1'], $row['path'])) { // ^[/]
156
-                unset($this->svgFileArr[$row['path']]);
157
-            }
158
-        }
159
-        unset($storageArr, $svgFileArr); // save MEM
160
-
161
-        $svg = preg_replace_callback(
162
-            '/<use(?<pre>.*?)(?:xlink:)?href="(?<href>\/.+?\.svg)#[^"]+"(?<post>.*?)[\s\/]*>(?:<\/use>)?/s',
163
-            function (array $match): string {
164
-                if (!isset($this->svgFileArr[$match['href']])) { // check usage
165
-                    return $match[0];
166
-                }
167
-
168
-                return sprintf('<use%s href="#%s"/>', $match['pre'].$match['post'], $this->convertFilePath($match['href']));
169
-            },
170
-            '<svg xmlns="http://www.w3.org/2000/svg">'
171
-            //."\n<style>\n".implode("\n", $this->styl)."\n</style>"
172
-            //."\n<defs>\n".implode("\n", $this->defs)."\n</defs>"
173
-            ."\n<symbol ".implode("</symbol>\n<symbol ", $this->svgs)."</symbol>\n"
174
-            .'</svg>'
175
-        );
176
-
177
-        //unset($this->styl); // save MEM
178
-        //unset($this->defs); // save MEM
179
-        unset($this->svgs); // save MEM
180
-
181
-        if (\is_int($var = $GLOBALS['TSFE']->config['config']['sourceopt.']['formatHtml']) && 1 == $var) {
182
-            $svg = preg_replace('/[\n\r\t\v\0]|\s{2,}/', '', $svg);
183
-        }
184
-
185
-        $svg = preg_replace('/<([a-z]+)\s*(\/|>\s*<\/\1)>\s*/i', '', $svg); // remove emtpy
186
-        $svg = preg_replace('/<((circle|ellipse|line|path|polygon|polyline|rect|stop|use)\s[^>]+?)\s*>\s*<\/\2>/', '<$1/>', $svg); // shorten/minify
187
-
188
-        if (!is_dir($this->sitePath.$this->outputDir)) {
189
-            GeneralUtility::mkdir_deep($this->sitePath.$this->outputDir);
190
-        }
191
-
192
-        $this->spritePath = $this->outputDir.hash('sha1', serialize($this->svgFileArr)).'.svg';
193
-        if (false === file_put_contents($this->sitePath.$this->spritePath, $svg)) {
194
-            return false;
195
-        }
196
-
197
-        $this->svgCache->set('spritePath', $this->spritePath);
198
-        $this->svgCache->set('svgFileArr', $this->svgFileArr);
199
-
200
-        return true;
201
-    }
84
+		if (1 === preg_match('/(?:;base64|i:a?i?pgf)/', $svg = file_get_contents($this->sitePath.$path))) { // noop!
85
+			return null;
86
+		}
87
+
88
+		if (1 === preg_match('/<(?:style|defs)|url\(/', $svg)) {
89
+			return null; // check links @ __construct
90
+		}
91
+
92
+		//$svg = preg_replace('/((?:id|class)=")/', '$1'.$hash.'__', $svg); // extend  IDs
93
+		//$svg = preg_replace('/(href="|url\()#/', '$1#'.$hash.'__', $svg); // recover IDs
94
+
95
+		//$svg = preg_replace_callback('/<style[^>]*>(?<styl>.+?)<\/style>|<defs[^>]*>(?<defs>.+?)<\/defs>/s', function(array $match) use($hash): string {
96
+		//
97
+		//    if(isset($match['styl']))
98
+		//    {
99
+		//        $this->styl[] = preg_replace('/\s*(\.|#){1}(.+?)\s*\{/', '$1'.$hash.'__$2{', $match['styl']); // patch CSS # https://mathiasbynens.be/notes/css-escapes
100
+		//    }
101
+		//    if(isset($match['defs']))
102
+		//    {
103
+		//        $this->defs[] = trim($match['defs']);
104
+		//    }
105
+		//    return '';
106
+		//}, $svg);
107
+
108
+		// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href
109
+		$svg = preg_replace('/^.*?<svg|\s*(<\/svg>)(?!.*\1).*$|xlink:|\s(?:(?:version|xmlns)|(?:[a-z\-]+\:[a-z\-]+))="[^"]*"/s', '', $svg); // cleanup
110
+
111
+		// https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg#attributes
112
+		$svg = preg_replace_callback('/([^>]*)\s*(?=>)/s', function (array $match) use (&$attr): string {
113
+			if (false === preg_match_all('/(?!\s)(?<attr>[\w\-]+)="\s*(?<value>[^"]+)\s*"/', $match[1], $matches)) {
114
+				return $match[0];
115
+			}
116
+			foreach ($matches['attr'] as $index => $attribute) {
117
+				switch ($attribute) {
118
+				  case 'id':
119
+				  case 'width':
120
+				  case 'height':
121
+					  unset($matches[0][$index]);
122
+					  break;
123
+
124
+				  case 'viewBox':
125
+					  if (false !== preg_match('/\S+\s\S+\s\+?(?<width>[\d\.]+)\s\+?(?<height>[\d\.]+)/', $matches['value'][$index], $match)) {
126
+						  $attr[] = sprintf('%s="0 0 %s %s"', $attribute, $match['width'], $match['height']); // save!
127
+					  }
128
+				}
129
+			}
130
+
131
+			return implode(' ', $matches[0]);
132
+		}, $svg, 1);
133
+
134
+		if ($attr) { // TODO; beautify
135
+			$this->svgs[] = sprintf('id="%s" %s', $this->convertFilePath($path), $svg); // prepend ID
136
+
137
+			return ['attr' => implode(' ', $attr), 'hash' => $hash];
138
+		}
139
+
140
+		return null;
141
+	}
142
+
143
+	private function populateCache(): bool
144
+	{
145
+		$storageArr = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class)->findAll();
146
+		foreach ($storageArr as $storage) {
147
+			if ('relative' == $storage->getConfiguration()['pathType']) {
148
+				$storageArr[$storage->getUid()] = rtrim($storage->getConfiguration()['basePath'], '/'); // [^/]$
149
+			}
150
+		}
151
+		unset($storageArr[0]); // keep!
152
+
153
+		$svgFileArr = GeneralUtility::makeInstance(\HTML\Sourceopt\Resource\SvgFileRepository::class)->findAllByStorageUids(\array_keys($storageArr));
154
+		foreach ($svgFileArr as $index => $row) {
155
+			if (!$this->svgFileArr[($row['path'] = '/'.$storageArr[$row['storage']].$row['identifier'])] = $this->addFileToSpriteArr($row['sha1'], $row['path'])) { // ^[/]
156
+				unset($this->svgFileArr[$row['path']]);
157
+			}
158
+		}
159
+		unset($storageArr, $svgFileArr); // save MEM
160
+
161
+		$svg = preg_replace_callback(
162
+			'/<use(?<pre>.*?)(?:xlink:)?href="(?<href>\/.+?\.svg)#[^"]+"(?<post>.*?)[\s\/]*>(?:<\/use>)?/s',
163
+			function (array $match): string {
164
+				if (!isset($this->svgFileArr[$match['href']])) { // check usage
165
+					return $match[0];
166
+				}
167
+
168
+				return sprintf('<use%s href="#%s"/>', $match['pre'].$match['post'], $this->convertFilePath($match['href']));
169
+			},
170
+			'<svg xmlns="http://www.w3.org/2000/svg">'
171
+			//."\n<style>\n".implode("\n", $this->styl)."\n</style>"
172
+			//."\n<defs>\n".implode("\n", $this->defs)."\n</defs>"
173
+			."\n<symbol ".implode("</symbol>\n<symbol ", $this->svgs)."</symbol>\n"
174
+			.'</svg>'
175
+		);
176
+
177
+		//unset($this->styl); // save MEM
178
+		//unset($this->defs); // save MEM
179
+		unset($this->svgs); // save MEM
180
+
181
+		if (\is_int($var = $GLOBALS['TSFE']->config['config']['sourceopt.']['formatHtml']) && 1 == $var) {
182
+			$svg = preg_replace('/[\n\r\t\v\0]|\s{2,}/', '', $svg);
183
+		}
184
+
185
+		$svg = preg_replace('/<([a-z]+)\s*(\/|>\s*<\/\1)>\s*/i', '', $svg); // remove emtpy
186
+		$svg = preg_replace('/<((circle|ellipse|line|path|polygon|polyline|rect|stop|use)\s[^>]+?)\s*>\s*<\/\2>/', '<$1/>', $svg); // shorten/minify
187
+
188
+		if (!is_dir($this->sitePath.$this->outputDir)) {
189
+			GeneralUtility::mkdir_deep($this->sitePath.$this->outputDir);
190
+		}
191
+
192
+		$this->spritePath = $this->outputDir.hash('sha1', serialize($this->svgFileArr)).'.svg';
193
+		if (false === file_put_contents($this->sitePath.$this->spritePath, $svg)) {
194
+			return false;
195
+		}
196
+
197
+		$this->svgCache->set('spritePath', $this->spritePath);
198
+		$this->svgCache->set('svgFileArr', $this->svgFileArr);
199
+
200
+		return true;
201
+	}
202 202
 }
Please login to merge, or discard this patch.