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