-
-
Notifications
You must be signed in to change notification settings - Fork 200
/
ScssParser.php
185 lines (170 loc) · 7.78 KB
/
ScssParser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
<?php declare(strict_types=1);
/*
* This file is part of the package bk2k/bootstrap-package.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/
namespace BK2K\BootstrapPackage\Parser;
use ScssPhp\ScssPhp\Compiler;
use ScssPhp\ScssPhp\OutputStyle;
use ScssPhp\ScssPhp\Version;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\PathUtility;
/**
* ScssParser
*/
class ScssParser extends AbstractParser
{
/**
* Constructor
*/
public function __construct()
{
if (!class_exists('ScssPhp\ScssPhp\Version')) {
require_once ExtensionManagementUtility::extPath('bootstrap_package') . '/Contrib/scssphp/scss.inc.php';
}
}
/**
* @param string $extension
* @return bool
*/
public function supports(string $extension): bool
{
return $extension === 'scss';
}
/**
* @param string $file
* @param array $settings
* @return string
*/
public function compile(string $file, array $settings): string
{
$cacheIdentifier = $this->getCacheIdentifier($file, $settings);
$cacheFile = $this->getCacheFile($cacheIdentifier, $settings['cache']['tempDirectory']);
$cacheFileMeta = $this->getCacheFileMeta($cacheFile);
$cacheFileMap = $this->getCacheFileMap($cacheFile);
$compile = false;
if (!$this->isCached($file, $settings)
|| $this->needsCompile($cacheFile, $cacheFileMeta, $settings)) {
$compile = true;
}
if ($compile) {
$result = $this->parseFile($file, $settings);
if ($settings['options']['sourceMap']) {
// Write css file and append reference to source map file
GeneralUtility::writeFile(
GeneralUtility::getFileAbsFileName($cacheFile),
sprintf('%s /*# sourceMappingURL=%s */', $result['css'], basename($cacheFileMap))
);
// Write map file
GeneralUtility::writeFile(GeneralUtility::getFileAbsFileName($cacheFileMap), $result['sourceMap']);
} else {
// Write css file
GeneralUtility::writeFile(GeneralUtility::getFileAbsFileName($cacheFile), $result['css']);
}
GeneralUtility::writeFile(GeneralUtility::getFileAbsFileName($cacheFileMeta), serialize($result['cache']));
$this->clearPageCaches();
}
return $cacheFile;
}
/**
* @param string $file
* @param array $settings
* @return array
*/
protected function parseFile(string $file, array $settings): array
{
$scss = new Compiler();
$scss->setOutputStyle(OutputStyle::COMPRESSED);
$scss->addVariables($settings['variables']);
if ($settings['options']['sourceMap']) {
$scss->setSourceMap(Compiler::SOURCE_MAP_FILE);
$scss->setSourceMapOptions([
'sourceMapRootpath' => $settings['cache']['tempDirectoryRelativeToRoot'],
'sourceMapBasepath' => Environment::getProjectPath(),
'outputSourceFiles' => true,
]);
}
$absoluteFilename = $settings['file']['absolute'];
// Adds visual directory path of the initial file as import path
// This scenarios happens, when e.g. developing packages using the `path`
// repository feature of Composer - having one package in `public/typo3conf/ext/`
// and the other one symlinked in e.g. `packages/`.
// Since the PHP SCSS parser works on resolved real paths, the symlinked context is lost.
$visualImportPath = dirname($absoluteFilename);
$scss->addImportPath(function ($url) use ($visualImportPath): ?string {
// Resolve potential back paths manually using PathUtility::getCanonicalPath,
// but make sure we do not break out of TYPO3 application path using GeneralUtility::getFileAbsFileName
// Also resolve EXT: paths if given
$isTypo3Absolute = (strpos($url, 'EXT:') === 0) || PathUtility::isAbsolutePath($url);
$fileName = $isTypo3Absolute ? $url : $visualImportPath . '/' . $url;
$full = GeneralUtility::getFileAbsFileName(PathUtility::getCanonicalPath($fileName));
// The API forces us to check the existence of files paths, with or without url.
// We must only return a string if the file to be imported actually exists.
$hasExtension = (bool) preg_match('/[.]s?css$/', $url);
if (
is_file($file = $full . '.scss') ||
($hasExtension && is_file($file = $full))
) {
// We could trigger a deprecation message here at some point
return $file;
}
return null;
});
// Add extensions path to import paths, so that we can use paths relative to this directory to resolve imports
$scss->addImportPath(Environment::getExtensionsPath());
// Make paths in url() statements relative to site root
$absoluteFilePath = dirname($absoluteFilename);
$relativeFilePath = PathUtility::getAbsoluteWebPath($absoluteFilePath);
$absoluteBootstrapPackageThemePath =
ExtensionManagementUtility::extPath('bootstrap_package') . 'Resources/Public/Scss/Theme';
$relativeBootstrapPackageThemePath = PathUtility::getAbsoluteWebPath($absoluteBootstrapPackageThemePath);
$scss->registerFunction(
'url',
function ($args) use (
$scss,
$absoluteFilePath,
$relativeFilePath,
$absoluteBootstrapPackageThemePath,
$relativeBootstrapPackageThemePath
) : string {
$marker = $args[0][1];
$args[0][1] = '';
$result = $scss->compileValue($args[0]);
if (substr_compare($result, 'data:', 0, 5, true) !== 0) {
if (is_file(PathUtility::getCanonicalPath($absoluteFilePath . '/' . $result))) {
$result = PathUtility::getCanonicalPath($relativeFilePath . '/' . $result);
} elseif (is_file(PathUtility::getCanonicalPath($absoluteBootstrapPackageThemePath . '/' . $result))) {
$result = PathUtility::getCanonicalPath($relativeBootstrapPackageThemePath . '/' . $result);
}
$result = substr($result, 0, 1) === '/' ? substr($result, 1) : $result;
}
return 'url(' . $marker . $result . $marker . ')';
}
);
// Compile file. Second parameter is needed for source mapping
$compilationResult = $scss->compileString('@import "' . $absoluteFilename . '"', $absoluteFilename);
$css = $compilationResult->getCss();
// Fix paths in url() statements to be relative to temp directory
$relativeTempPath = $settings['cache']['tempDirectoryRelativeToRoot'];
$search = '%url\s*\(\s*[\\\'"]?(?!(((?:https?:)?\/\/)|(?:data:?:)))([^\\\'")]+)[\\\'"]?\s*\)%';
$replace = 'url("' . $relativeTempPath . '$3")';
$css = (string) preg_replace($search, $replace, $css);
return [
'css' => $css,
'sourceMap' => $compilationResult->getSourceMap(),
'cache' => [
'version' => Version::VERSION,
'date' => date('r'),
'css' => $css,
'etag' => md5($css),
'files' => $compilationResult->getIncludedFiles(),
'variables' => $settings['variables'],
'sourceMap' => $settings['options']['sourceMap']
]
];
}
}