/
sfLESS.class.php
545 lines (487 loc) · 13 KB
/
sfLESS.class.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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
<?php
/*
* This file is part of the sfLESSPlugin.
* (c) 2010 Konstantin Kudryashov <ever.zet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfLESS is helper class to provide LESS compiling in symfony projects.
*
* @package sfLESSPlugin
* @subpackage lib
* @author Konstantin Kudryashov <ever.zet@gmail.com>
* @version 1.0.0
*/
class sfLESS
{
/**
* Array of LESS styles
*
* @var array
**/
protected static $results = array();
/**
* Errors of compiler
*
* @var array
**/
protected static $errors = array();
/**
* Do we need to check dates before compile
*
* @var boolean
*/
protected $checkDates = true;
/**
* Do we need compression for CSS files
*
* @var boolean
*/
protected $useCompression = false;
/**
* Current LESS file to be parsed. This var used to help output errors in callCompiler()
*
* @var string
*/
protected $currentFile;
/**
* Constructor
*
* @param boolean $checkDates Do we need to check dates before compile
* @param boolean $useCompression Do we need compression for CSS files
*/
public function __construct($checkDates = true, $useCompression = false)
{
$this->setIsCheckDates($checkDates);
$this->setIsUseCompression($useCompression);
}
/**
* Returns array of compiled styles info
*
* @return array
*/
public static function getCompileResults()
{
return self::$results;
}
/**
* Returns array of compiled styles errors
*
* @return array
*/
public static function getCompileErrors()
{
return self::$errors;
}
/**
* Returns debug info of the current state
*
* @return array state
*/
public function getDebugInfo()
{
return array(
'dates' => var_export($this->isCheckDates(), true),
'compress' => var_export($this->isUseCompression(), true),
'less' => $this->getLessPaths(),
'css' => $this->getCssPaths()
);
}
/**
* Returns path with changed directory separators to unix-style (\ => /)
*
* @param string $path basic path
*
* @return string unix-style path
*/
public static function getSepFixedPath($path)
{
return str_replace(DIRECTORY_SEPARATOR, '/', $path);
}
/**
* Returns relative path from the project root dir
*
* @param string $fullPath full path to file
*
* @return string relative path from the project root
*/
public static function getProjectRelativePath($fullPath)
{
return str_replace(
self::getSepFixedPath(sfConfig::get('sf_root_dir')) . '/',
'',
self::getSepFixedPath($fullPath)
);
}
/**
* Do we need to check dates before compile
*
* @return boolean
*/
public function isCheckDates()
{
return sfConfig::get('app_sf_less_plugin_check_dates', $this->checkDates);
}
/**
* Set need of check dates before compile
*
* @param boolean $checkDates Do we need to check dates before compile
*/
public function setIsCheckDates($checkDates)
{
$this->checkDates = $checkDates;
}
/**
* Do we need compression for CSS files
*
* @return boolean
*/
public function isUseCompression()
{
return sfConfig::get('app_sf_less_plugin_use_compression', $this->useCompression);
}
/**
* Set need of compression for CSS files
*
* @param boolean $useCompression Do we need compression for CSS files
*/
public function setIsUseCompression($useCompression)
{
$this->useCompression = $useCompression;
}
/**
* Returns paths to CSS files
*
* @return string a path to CSS files directory
*/
static public function getCssPaths()
{
return self::getSepFixedPath(sfConfig::get('sf_web_dir')) . '/css/';
}
/**
* Returns all CSS files under the CSS directory
*
* @return array an array of CSS files
*/
static public function findCssFiles()
{
return sfFinder::type('file')
->exec(array('sfLESS', 'isCssLessCompiled'))
->name('*.css')
->in(self::getCssPaths());
}
/**
* Returns header text for CSS files
*
* @return string a header text for CSS files
*/
static protected function getCssHeader()
{
return '/* This CSS is autocompiled by LESS parser. Don\'t edit it manually. */';
}
/**
* Checks if CSS file was compiled from LESS
*
* @param string $dir a path to file
* @param string $entry a filename
*
* @return boolean
*/
static public function isCssLessCompiled($dir, $entry)
{
$file = $dir . '/' . $entry;
$fp = fopen( $file, 'r' );
$line = stream_get_line($fp, 1024, "\n");
fclose($fp);
return (0 === strcmp($line, self::getCssHeader()));
}
/**
* Returns paths to LESS files
*
* @return string a path to LESS files directories
*/
static public function getLessPaths()
{
return self::getSepFixedPath(sfConfig::get('sf_web_dir')) . '/less/';
}
/**
* Returns all LESS files under the LESS directories
*
* @return array an array of LESS files
*/
static public function findLessFiles()
{
return sfFinder::type('file')
->name('*.less')
->discard('_*')
->follow_link()
->in(self::getLessPaths());
}
/**
* Returns CSS file path by its LESS alternative
*
* @param string $lessFile LESS file path
*
* @return string CSS file path
*/
static public function getCssPathOfLess($lessFile)
{
return str_replace(
array(self::getLessPaths(), '.less'),
array(self::getCssPaths(), '.css'),
$lessFile
);
}
/**
* Update the response by fixing less stylesheet path and adding the less js engine when required
*
* @param sfWebResponse $response The response that will be sent back to the browser
* @param boolean $useJs Wether the less stylesheets should be processed by the js on the client side
*/
static public function findAndFixContentLinks(sfWebResponse $response, $useJs)
{
$hasLess = false;
foreach ($response->getStylesheets() as $file => $options)
{
if ('.less' === substr($file, -5) && (!isset($options['rel']) || 'stylesheet/less' !== $options['rel']))
{
$response->removeStylesheet($file);
if ($useJs)
{
$response->addStylesheet('/less/' . $file, '', array_merge($options, array('rel' => 'stylesheet/less')));
$hasLess = true;
}
else
{
$response->addStylesheet('/css/' . substr($file, 0, -5) . '.css', '', $options);
}
}
}
if ($hasLess)
{
$response->addJavascript(
sfConfig::get('app_sf_less_plugin_js_lib', '/sfLESSPlugin/js/less-1.0.30.min.js')
);
}
}
/**
* Listens to the routing.load_configuration event. Finds & compiles LESS files to CSS
*
* @param sfEvent $event an sfEvent instance
*/
static public function findAndCompile(sfEvent $event)
{
// Start compilation timer for debug info
$timer = sfTimerManager::getTimer('Less compilation');
// Create new helper object & compile LESS stylesheets with it
$lessHelper = new self;
foreach (self::findLessFiles() as $lessFile)
{
$lessHelper->compile($lessFile);
}
// Stop timer
$timer->addTime();
}
/**
* Compiles LESS file to CSS
*
* @param string $lessFile a LESS file
*
* @return boolean true if succesfully compiled & false in other way
*/
public function compile($lessFile)
{
// Creates timer
$timer = new sfTimer;
// Gets CSS file path
$cssFile = self::getCssPathOfLess($lessFile);
// Checks if path exists & create if not
if (!is_dir(dirname($cssFile)))
{
mkdir(dirname($cssFile), 0777, true);
// PHP workaround to fix nested folders
chmod(dirname($cssFile), 0777);
}
// Is file compiled
$isCompiled = false;
// If we check dates - recompile only really old CSS
if ($this->isCheckDates())
{
$isCompiled = $this->checkDatesAndDependencies($lessFile,
sfConfig::get('app_sf_less_plugin_check_dependencies', false));
}
else
{
$isCompiled = $this->callCompiler($lessFile, $cssFile);
}
// Adds debug info to debug array
self::$results[] = array(
'lessFile' => $lessFile,
'cssFile' => $cssFile,
'compTime' => $timer->getElapsedTime(),
'isCompiled' => $isCompiled
);
return $isCompiled;
}
/**
* Compiles the files only if the target file (.css) is older than the source file (.less),
* or optionally older than any of the dependecies.
*
* @param string $lessFile The source file
* @param boolean $checkDeps Wether the dependencies should be taken into account
* @return boolean Wheter the file has been compiled
*/
protected function checkDatesAndDependencies($lessFile, $checkDeps)
{
// The files we depend on
$deps = array();
$mtime = filemtime($lessFile);
// Gets CSS file path
$cssFile = self::getCssPathOfLess($lessFile);
if (!is_file($cssFile))
{
// Always call the compiler when the target does not exist
return $this->callCompiler($lessFile, $cssFile);
}
else
{
if ($checkDeps)
{
// Compute the less file dependencies and the date of the last modified file
$d = new sfLESSDependency(self::getLessPaths());
$deps = $d->computeDependencies($lessFile, $deps);
foreach ($deps as $file)
{
if (is_file($file))
{
$mtime = max($mtime, filemtime($file));
}
}
}
// Compile the file if the modification date occurs after the target file date
if ($mtime > filemtime($cssFile))
{
return $this->callCompiler($lessFile, $cssFile);
}
else
{
return false;
}
}
}
/**
* Compress CSS by removing whitespaces, tabs, newlines, etc.
*
* @param string $css CSS to be compressed
*
* @return string compressed CSS
*/
static public function getCompressedCss($css)
{
return str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $css);
}
/**
* Calls current LESS compiler for single file
*
* @param string $lessFile a LESS file
* @param string $cssFile a CSS file
*
* @return boolean true if succesfully compiled & false in other way
*/
public function callCompiler($lessFile, $cssFile)
{
// Setting current file. We will output this var if compiler throws error
$this->currentFile = $lessFile;
// Do not try to change the permission of an existing file which we might not own
$setPermission = !is_file($cssFile);
// Call compiler
$buffer = $this->callLesscCompiler($lessFile, $cssFile);
// Checks if compiler returns false
if (false === $buffer)
{
return $buffer;
}
// Compress CSS if we use compression
if ($this->isUseCompression())
{
$buffer = self::getCompressedCss($buffer);
}
// Add compiler header to CSS & writes it to file
file_put_contents($cssFile, self::getCssHeader() . "\n\n" . $buffer);
if ($setPermission)
{
// Set permissions for fresh files only
chmod($cssFile, 0666);
}
// Setting current file to null
$this->currentFile = null;
return true;
}
/**
* Calls lessc compiler for LESS file
*
* @param string $lessFile a LESS file
* @param string $cssFile a CSS file
*
* @return string output
*/
public function callLesscCompiler($lessFile, $cssFile)
{
// Compile with lessc
$fs = new sfFilesystem;
$command = sprintf('lessc "%s" "%s"', $lessFile, $cssFile);
if ('1.3.0' <= SYMFONY_VERSION)
{
try
{
$fs->execute($command, null, array($this, 'throwCompilerError'));
}
catch (RuntimeException $e)
{
return false;
}
}
else
{
$fs->sh($command);
}
return file_get_contents($cssFile);
}
/**
* Returns true if compiler can throw RuntimeException
*
* @return boolean
*/
public function canThrowExceptions()
{
return (('prod' !== sfConfig::get('sf_environment') || !sfConfig::get('sf_app')) &&
!(sfConfig::get('sf_web_debug') && sfConfig::get('app_sf_less_plugin_toolbar', true))
);
}
/**
* Throws formatted compiler error
*
* @param string $line error line
*
* @return boolean
*/
public function throwCompilerError($line)
{
// Generate error description
$errorDescription = sprintf("LESS parser error in \"%s\":\n\n%s", $this->currentFile, $line);
// Adds error description to list of errors
self::$errors[$this->currentFile] = $errorDescription;
// Throw exception if allowed & log error otherwise
if ($this->canThrowExceptions())
{
throw new sfException($errorDescription);
}
else
{
sfContext::getInstance()->getLogger()->err($errorDescription);
}
return false;
}
}