Completed
Push — master ( 0e515f...2cae92 )
by Tim
20s queued 11s
created
Classes/Service/SvgStoreService.php 2 patches
Indentation   +180 added lines, -180 removed lines patch added patch discarded remove patch
@@ -13,184 +13,184 @@
 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|<\/svg>.*|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
-                      $attr[] = sprintf('%s="%s"', $attribute, $matches['value'][$index]); // save!
122
-                }
123
-            }
124
-
125
-            return implode(' ', $matches[0]);
126
-        }, $svg, 1);
127
-
128
-        if ($attr) { // TODO; beautify
129
-            $this->svgs[] = sprintf('id="%s" %s', $this->convertFilePath($path), $svg); // append ID
130
-
131
-            return ['attr' => implode(' ', $attr), 'hash' => $hash];
132
-        }
133
-
134
-        return null;
135
-    }
136
-
137
-    private function populateCache(): bool
138
-    {
139
-        $storageArr = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class)->findAll();
140
-        foreach ($storageArr as $storage) {
141
-            if ('relative' == $storage->getConfiguration()['pathType']) {
142
-                $storageArr[$storage->getUid()] = rtrim($storage->getConfiguration()['basePath'], '/'); // [^/]$
143
-            }
144
-        }
145
-        unset($storageArr[0]); // keep!
146
-
147
-        $svgFileArr = GeneralUtility::makeInstance(\HTML\Sourceopt\Resource\SvgFileRepository::class)->findAllByStorageUids(array_keys($storageArr));
148
-        foreach ($svgFileArr as $index => $row) {
149
-            if (!$this->svgFileArr[($row['path'] = '/'.$storageArr[$row['storage']].$row['identifier'])] = $this->addFileToSpriteArr($row['sha1'], $row['path'])) { // ^[/]
150
-                unset($this->svgFileArr[$row['path']]);
151
-            }
152
-        }
153
-        unset($storageArr, $svgFileArr); // save MEM
154
-
155
-        $svg = preg_replace_callback(
156
-            '/<use(?<pre>.*?)(?:xlink:)?href="(?<href>\/.+?\.svg)#[^"]+"(?<post>.*?)[\s\/]*>(?:<\/use>)?/s',
157
-            function (array $match): string {
158
-                if (!isset($this->svgFileArr[$match['href']])) { // check usage
159
-                    return $match[0];
160
-                }
161
-
162
-                return sprintf('<use%s href="#%s"/>', $match['pre'].$match['post'], $this->convertFilePath($match['href']));
163
-            },
164
-            '<svg xmlns="http://www.w3.org/2000/svg">'
165
-            //."\n<style>\n".implode("\n", $this->styl)."\n</style>"
166
-            //."\n<defs>\n".implode("\n", $this->defs)."\n</defs>"
167
-            ."\n<symbol ".implode("</symbol>\n<symbol ", $this->svgs)."</symbol>\n"
168
-            .'</svg>'
169
-        );
170
-
171
-        //unset($this->styl); // save MEM
172
-        //unset($this->defs); // save MEM
173
-        unset($this->svgs); // save MEM
174
-
175
-        if (\is_int($var = $GLOBALS['TSFE']->config['config']['sourceopt.']['formatHtml']) && 1 == $var) {
176
-            $svg = preg_replace('/[\n\r\t\v\0]|\s{2,}/', '', $svg);
177
-        }
178
-
179
-        $svg = preg_replace('/<([a-z]+)\s*(\/|>\s*<\/\1)>\s*/i', '', $svg); // remove emtpy
180
-        $svg = preg_replace('/<((circle|ellipse|line|path|polygon|polyline|rect|stop|use)\s[^>]+?)\s*>\s*<\/\2>/', '<$1/>', $svg); // shorten/minify
181
-
182
-        if (!is_dir($this->sitePath.$this->outputDir)) {
183
-            GeneralUtility::mkdir_deep($this->sitePath.$this->outputDir);
184
-        }
185
-
186
-        $this->spritePath = $this->outputDir.hash('sha1', serialize($this->svgFileArr)).'.svg';
187
-        if (false === file_put_contents($this->sitePath.$this->spritePath, $svg)) {
188
-            return false;
189
-        }
190
-
191
-        $this->svgCache->set('svgFileArr', $this->svgFileArr);
192
-        $this->svgCache->set('spritePath', $this->spritePath);
193
-
194
-        return true;
195
-    }
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|<\/svg>.*|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
+					  $attr[] = sprintf('%s="%s"', $attribute, $matches['value'][$index]); // save!
122
+				}
123
+			}
124
+
125
+			return implode(' ', $matches[0]);
126
+		}, $svg, 1);
127
+
128
+		if ($attr) { // TODO; beautify
129
+			$this->svgs[] = sprintf('id="%s" %s', $this->convertFilePath($path), $svg); // append ID
130
+
131
+			return ['attr' => implode(' ', $attr), 'hash' => $hash];
132
+		}
133
+
134
+		return null;
135
+	}
136
+
137
+	private function populateCache(): bool
138
+	{
139
+		$storageArr = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class)->findAll();
140
+		foreach ($storageArr as $storage) {
141
+			if ('relative' == $storage->getConfiguration()['pathType']) {
142
+				$storageArr[$storage->getUid()] = rtrim($storage->getConfiguration()['basePath'], '/'); // [^/]$
143
+			}
144
+		}
145
+		unset($storageArr[0]); // keep!
146
+
147
+		$svgFileArr = GeneralUtility::makeInstance(\HTML\Sourceopt\Resource\SvgFileRepository::class)->findAllByStorageUids(array_keys($storageArr));
148
+		foreach ($svgFileArr as $index => $row) {
149
+			if (!$this->svgFileArr[($row['path'] = '/'.$storageArr[$row['storage']].$row['identifier'])] = $this->addFileToSpriteArr($row['sha1'], $row['path'])) { // ^[/]
150
+				unset($this->svgFileArr[$row['path']]);
151
+			}
152
+		}
153
+		unset($storageArr, $svgFileArr); // save MEM
154
+
155
+		$svg = preg_replace_callback(
156
+			'/<use(?<pre>.*?)(?:xlink:)?href="(?<href>\/.+?\.svg)#[^"]+"(?<post>.*?)[\s\/]*>(?:<\/use>)?/s',
157
+			function (array $match): string {
158
+				if (!isset($this->svgFileArr[$match['href']])) { // check usage
159
+					return $match[0];
160
+				}
161
+
162
+				return sprintf('<use%s href="#%s"/>', $match['pre'].$match['post'], $this->convertFilePath($match['href']));
163
+			},
164
+			'<svg xmlns="http://www.w3.org/2000/svg">'
165
+			//."\n<style>\n".implode("\n", $this->styl)."\n</style>"
166
+			//."\n<defs>\n".implode("\n", $this->defs)."\n</defs>"
167
+			."\n<symbol ".implode("</symbol>\n<symbol ", $this->svgs)."</symbol>\n"
168
+			.'</svg>'
169
+		);
170
+
171
+		//unset($this->styl); // save MEM
172
+		//unset($this->defs); // save MEM
173
+		unset($this->svgs); // save MEM
174
+
175
+		if (\is_int($var = $GLOBALS['TSFE']->config['config']['sourceopt.']['formatHtml']) && 1 == $var) {
176
+			$svg = preg_replace('/[\n\r\t\v\0]|\s{2,}/', '', $svg);
177
+		}
178
+
179
+		$svg = preg_replace('/<([a-z]+)\s*(\/|>\s*<\/\1)>\s*/i', '', $svg); // remove emtpy
180
+		$svg = preg_replace('/<((circle|ellipse|line|path|polygon|polyline|rect|stop|use)\s[^>]+?)\s*>\s*<\/\2>/', '<$1/>', $svg); // shorten/minify
181
+
182
+		if (!is_dir($this->sitePath.$this->outputDir)) {
183
+			GeneralUtility::mkdir_deep($this->sitePath.$this->outputDir);
184
+		}
185
+
186
+		$this->spritePath = $this->outputDir.hash('sha1', serialize($this->svgFileArr)).'.svg';
187
+		if (false === file_put_contents($this->sitePath.$this->spritePath, $svg)) {
188
+			return false;
189
+		}
190
+
191
+		$this->svgCache->set('svgFileArr', $this->svgFileArr);
192
+		$this->svgCache->set('spritePath', $this->spritePath);
193
+
194
+		return true;
195
+	}
196 196
 }
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|<\/svg>.*|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
             }
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
 
155 155
         $svg = preg_replace_callback(
156 156
             '/<use(?<pre>.*?)(?:xlink:)?href="(?<href>\/.+?\.svg)#[^"]+"(?<post>.*?)[\s\/]*>(?:<\/use>)?/s',
157
-            function (array $match): string {
157
+            function(array $match): string {
158 158
                 if (!isset($this->svgFileArr[$match['href']])) { // check usage
159 159
                     return $match[0];
160 160
                 }
Please login to merge, or discard this patch.