1 <?php
2 3 4 5 6 7
8
9 namespace Hawk;
10
11 12 13 14 15
16 class Less{
17 const CACHE_DIR = 'less/';
18
19 20 21
22 private $source;
23
24 25 26 27 28
29 public function __construct($source){
30 if(!is_file($source)) {
31 throw new \Exception('Impossible to compile the file ' . $source . ' : No such file');
32 }
33
34 $this->source = $source;
35 }
36
37 38 39 40 41
42 private function getLastCompilationInfoFilename(){
43 return 'less/' . str_replace(array(ROOT_DIR, '/'), array('', '-'), realpath($this->source));
44 }
45
46 47 48 49 50
51 private function saveLastCompilationInfo($info){
52 App::cache()->save($this->getLastCompilationInfoFilename(), '<?php return ' . var_export($info, true) . ';');
53 }
54
55 56 57 58 59 60 61
62 public function build($dest, $force = false, $variables = array()){
63 if(!is_dir(dirname($dest))) {
64 mkdir(dirname($dest), 0755, true);
65 }
66
67 $compiler = new \lessc;
68
69
70 $lastCompilationFile = App::cache()->getCacheFilePath($this->getLastCompilationInfoFilename());
71 if(!$force && is_file($lastCompilationFile)) {
72 $cache = include $lastCompilationFile;
73 }
74 else{
75 $cache = $this->source;
76 }
77
78 $compiler->setFormatter('compressed');
79 $compiler->setPreserveComments(false);
80 $compilation = $compiler->cachedCompile($cache, $force);
81
82 if(!is_array($cache) || $compilation['updated'] > $cache['updated']) {
83 file_put_contents($dest, '/*** ' . date('Y-m-d H:i:s') . ' ***/' . PHP_EOL . $compilation['compiled']);
84
85 $event = new Event('built-less', array('source' => $this->source, 'dest' => $dest));
86 $event->trigger();
87
88
89 unset($compilation['compiled']);
90 $this->saveLastCompilationInfo($compilation);
91 }
92 }
93
94
95 96 97 98 99 100 101 102
103 public static function compile($source, $dest, $force = false, $variables = array()){
104 $less = new self($source);
105
106 $less->build($dest, $force, $variables);
107 }
108 }