Generator.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. <?php
  2. /**
  3. * Source map generator
  4. *
  5. * @package Less
  6. * @subpackage Output
  7. */
  8. class Less_SourceMap_Generator extends Less_Configurable {
  9. /**
  10. * What version of source map does the generator generate?
  11. */
  12. private const VERSION = 3;
  13. /**
  14. * Array of default options
  15. *
  16. * @var array
  17. */
  18. protected $defaultOptions = array(
  19. // an optional source root, useful for relocating source files
  20. // on a server or removing repeated values in the 'sources' entry.
  21. // This value is prepended to the individual entries in the 'source' field.
  22. 'sourceRoot' => '',
  23. // an optional name of the generated code that this source map is associated with.
  24. 'sourceMapFilename' => null,
  25. // url of the map
  26. 'sourceMapURL' => null,
  27. // absolute path to a file to write the map to
  28. 'sourceMapWriteTo' => null,
  29. // output source contents?
  30. 'outputSourceFiles' => false,
  31. // base path for filename normalization
  32. 'sourceMapRootpath' => '',
  33. // base path for filename normalization
  34. 'sourceMapBasepath' => ''
  35. );
  36. /**
  37. * The base64 VLQ encoder
  38. *
  39. * @var Less_SourceMap_Base64VLQ
  40. */
  41. protected $encoder;
  42. /**
  43. * Array of mappings
  44. *
  45. * @var array
  46. */
  47. protected $mappings = array();
  48. /**
  49. * The root node
  50. *
  51. * @var Less_Tree_Ruleset
  52. */
  53. protected $root;
  54. /**
  55. * Array of contents map
  56. *
  57. * @var array
  58. */
  59. protected $contentsMap = array();
  60. /**
  61. * File to content map
  62. *
  63. * @var array
  64. */
  65. protected $sources = array();
  66. protected $source_keys = array();
  67. /**
  68. * Constructor
  69. *
  70. * @param Less_Tree_Ruleset $root The root node
  71. * @param array $options Array of options
  72. */
  73. public function __construct( Less_Tree_Ruleset $root, $contentsMap, $options = array() ) {
  74. $this->root = $root;
  75. $this->contentsMap = $contentsMap;
  76. $this->encoder = new Less_SourceMap_Base64VLQ();
  77. $this->SetOptions( $options );
  78. $this->options['sourceMapRootpath'] = $this->fixWindowsPath( $this->options['sourceMapRootpath'], true );
  79. $this->options['sourceMapBasepath'] = $this->fixWindowsPath( $this->options['sourceMapBasepath'], true );
  80. }
  81. /**
  82. * Generates the CSS
  83. *
  84. * @return string
  85. */
  86. public function generateCSS() {
  87. $output = new Less_Output_Mapped( $this->contentsMap, $this );
  88. // catch the output
  89. $this->root->genCSS( $output );
  90. $sourceMapUrl = $this->getOption( 'sourceMapURL' );
  91. $sourceMapFilename = $this->getOption( 'sourceMapFilename' );
  92. $sourceMapContent = $this->generateJson();
  93. $sourceMapWriteTo = $this->getOption( 'sourceMapWriteTo' );
  94. if ( !$sourceMapUrl && $sourceMapFilename ) {
  95. $sourceMapUrl = $this->normalizeFilename( $sourceMapFilename );
  96. }
  97. // write map to a file
  98. if ( $sourceMapWriteTo ) {
  99. $this->saveMap( $sourceMapWriteTo, $sourceMapContent );
  100. }
  101. // inline the map
  102. if ( !$sourceMapUrl ) {
  103. $sourceMapUrl = sprintf( 'data:application/json,%s', Less_Functions::encodeURIComponent( $sourceMapContent ) );
  104. }
  105. if ( $sourceMapUrl ) {
  106. $output->add( sprintf( '/*# sourceMappingURL=%s */', $sourceMapUrl ) );
  107. }
  108. return $output->toString();
  109. }
  110. /**
  111. * Saves the source map to a file
  112. *
  113. * @param string $file The absolute path to a file
  114. * @param string $content The content to write
  115. * @throws Exception If the file could not be saved
  116. */
  117. protected function saveMap( $file, $content ) {
  118. $dir = dirname( $file );
  119. // directory does not exist
  120. if ( !is_dir( $dir ) ) {
  121. // FIXME: create the dir automatically?
  122. throw new Exception( sprintf( 'The directory "%s" does not exist. Cannot save the source map.', $dir ) );
  123. }
  124. // FIXME: proper saving, with dir write check!
  125. if ( file_put_contents( $file, $content ) === false ) {
  126. throw new Exception( sprintf( 'Cannot save the source map to "%s"', $file ) );
  127. }
  128. return true;
  129. }
  130. /**
  131. * Normalizes the filename
  132. *
  133. * @param string $filename
  134. * @return string
  135. */
  136. protected function normalizeFilename( $filename ) {
  137. $filename = $this->fixWindowsPath( $filename );
  138. $rootpath = $this->getOption( 'sourceMapRootpath' );
  139. $basePath = $this->getOption( 'sourceMapBasepath' );
  140. // "Trim" the 'sourceMapBasepath' from the output filename.
  141. if ( is_string( $basePath ) && strpos( $filename, $basePath ) === 0 ) {
  142. $filename = substr( $filename, strlen( $basePath ) );
  143. }
  144. // Remove extra leading path separators.
  145. if ( strpos( $filename, '\\' ) === 0 || strpos( $filename, '/' ) === 0 ) {
  146. $filename = substr( $filename, 1 );
  147. }
  148. return $rootpath . $filename;
  149. }
  150. /**
  151. * Adds a mapping
  152. *
  153. * @param integer $generatedLine The line number in generated file
  154. * @param integer $generatedColumn The column number in generated file
  155. * @param integer $originalLine The line number in original file
  156. * @param integer $originalColumn The column number in original file
  157. * @param string $sourceFile The original source file
  158. */
  159. public function addMapping( $generatedLine, $generatedColumn, $originalLine, $originalColumn, $fileInfo ) {
  160. $this->mappings[] = array(
  161. 'generated_line' => $generatedLine,
  162. 'generated_column' => $generatedColumn,
  163. 'original_line' => $originalLine,
  164. 'original_column' => $originalColumn,
  165. 'source_file' => $fileInfo['currentUri']
  166. );
  167. $this->sources[$fileInfo['currentUri']] = $fileInfo['filename'];
  168. }
  169. /**
  170. * Generates the JSON source map
  171. *
  172. * @return string
  173. * @see https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#
  174. */
  175. protected function generateJson() {
  176. $sourceMap = array();
  177. $mappings = $this->generateMappings();
  178. // File version (always the first entry in the object) and must be a positive integer.
  179. $sourceMap['version'] = self::VERSION;
  180. // An optional name of the generated code that this source map is associated with.
  181. $file = $this->getOption( 'sourceMapFilename' );
  182. if ( $file ) {
  183. $sourceMap['file'] = $file;
  184. }
  185. // An optional source root, useful for relocating source files on a server or removing repeated values in the 'sources' entry. This value is prepended to the individual entries in the 'source' field.
  186. $root = $this->getOption( 'sourceRoot' );
  187. if ( $root ) {
  188. $sourceMap['sourceRoot'] = $root;
  189. }
  190. // A list of original sources used by the 'mappings' entry.
  191. $sourceMap['sources'] = array();
  192. foreach ( $this->sources as $source_uri => $source_filename ) {
  193. $sourceMap['sources'][] = $this->normalizeFilename( $source_filename );
  194. }
  195. // A list of symbol names used by the 'mappings' entry.
  196. $sourceMap['names'] = array();
  197. // A string with the encoded mapping data.
  198. $sourceMap['mappings'] = $mappings;
  199. if ( $this->getOption( 'outputSourceFiles' ) ) {
  200. // An optional list of source content, useful when the 'source' can't be hosted.
  201. // The contents are listed in the same order as the sources above.
  202. // 'null' may be used if some original sources should be retrieved by name.
  203. $sourceMap['sourcesContent'] = $this->getSourcesContent();
  204. }
  205. // less.js compat fixes
  206. if ( count( $sourceMap['sources'] ) && empty( $sourceMap['sourceRoot'] ) ) {
  207. unset( $sourceMap['sourceRoot'] );
  208. }
  209. return json_encode( $sourceMap );
  210. }
  211. /**
  212. * Returns the sources contents
  213. *
  214. * @return array|null
  215. */
  216. protected function getSourcesContent() {
  217. if ( empty( $this->sources ) ) {
  218. return;
  219. }
  220. $content = array();
  221. foreach ( $this->sources as $sourceFile ) {
  222. $content[] = file_get_contents( $sourceFile );
  223. }
  224. return $content;
  225. }
  226. /**
  227. * Generates the mappings string
  228. *
  229. * @return string
  230. */
  231. public function generateMappings() {
  232. if ( !count( $this->mappings ) ) {
  233. return '';
  234. }
  235. $this->source_keys = array_flip( array_keys( $this->sources ) );
  236. // group mappings by generated line number.
  237. $groupedMap = $groupedMapEncoded = array();
  238. foreach ( $this->mappings as $m ) {
  239. $groupedMap[$m['generated_line']][] = $m;
  240. }
  241. ksort( $groupedMap );
  242. $lastGeneratedLine = $lastOriginalIndex = $lastOriginalLine = $lastOriginalColumn = 0;
  243. foreach ( $groupedMap as $lineNumber => $line_map ) {
  244. while ( ++$lastGeneratedLine < $lineNumber ) {
  245. $groupedMapEncoded[] = ';';
  246. }
  247. $lineMapEncoded = array();
  248. $lastGeneratedColumn = 0;
  249. foreach ( $line_map as $m ) {
  250. $mapEncoded = $this->encoder->encode( $m['generated_column'] - $lastGeneratedColumn );
  251. $lastGeneratedColumn = $m['generated_column'];
  252. // find the index
  253. if ( $m['source_file'] ) {
  254. $index = $this->findFileIndex( $m['source_file'] );
  255. if ( $index !== false ) {
  256. $mapEncoded .= $this->encoder->encode( $index - $lastOriginalIndex );
  257. $lastOriginalIndex = $index;
  258. // lines are stored 0-based in SourceMap spec version 3
  259. $mapEncoded .= $this->encoder->encode( $m['original_line'] - 1 - $lastOriginalLine );
  260. $lastOriginalLine = $m['original_line'] - 1;
  261. $mapEncoded .= $this->encoder->encode( $m['original_column'] - $lastOriginalColumn );
  262. $lastOriginalColumn = $m['original_column'];
  263. }
  264. }
  265. $lineMapEncoded[] = $mapEncoded;
  266. }
  267. $groupedMapEncoded[] = implode( ',', $lineMapEncoded ) . ';';
  268. }
  269. return rtrim( implode( $groupedMapEncoded ), ';' );
  270. }
  271. /**
  272. * Finds the index for the filename
  273. *
  274. * @param string $filename
  275. * @return integer|false
  276. */
  277. protected function findFileIndex( $filename ) {
  278. return $this->source_keys[$filename];
  279. }
  280. /**
  281. * fix windows paths
  282. * @param string $path
  283. * @return string
  284. */
  285. public function fixWindowsPath( $path, $addEndSlash = false ) {
  286. $slash = ( $addEndSlash ) ? '/' : '';
  287. if ( !empty( $path ) ) {
  288. $path = str_replace( '\\', '/', $path );
  289. $path = rtrim( $path, '/' ) . $slash;
  290. }
  291. return $path;
  292. }
  293. }