PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/lessphp/SourceMap/Generator.php

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