diff --git a/README.md b/README.md index 1379ddce..d3d87168 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ result or write it to the path specified by an optional second argument. echo $less->compileFile("input.less"); ``` -The `compileChecked` method is like `compileFile`, but it only compiles if the output +The `checkedCompile` method is like `compileFile`, but it only compiles if the output file doesn't exist or it's older than the input file: ```php diff --git a/docs/docs.md b/docs/docs.md index 112dc2ee..00a81d4b 100644 --- a/docs/docs.md +++ b/docs/docs.md @@ -1023,7 +1023,7 @@ result or write it to the path specified by an optional second argument. echo $less->compileFile("input.less"); ``` -The `compileChecked` method is like `compileFile`, but it only compiles if the output +The `checkedCompile` method is like `compileFile`, but it only compiles if the output file doesn't exist or it's older than the input file: ```php diff --git a/lessc.inc.php b/lessc.inc.php index 2292f219..294e7f9c 100644 --- a/lessc.inc.php +++ b/lessc.inc.php @@ -1930,6 +1930,43 @@ public function compileFile($fname, $outFname = null) { return $out; } + /** + * Based on explicit input/output files does a full change check on cache before compiling. + * + * @param string $in + * @param string $out + * @param boolean $force + * @return string Compiled CSS results + * @throws Exception + */ + public function checkedCachedCompile($in, $out, $force = false) { + if (!is_file($in) || !is_readable($in)) { + throw new Exception('Invalid or unreadable input file specified.'); + } + if (is_dir($out) || !is_writable(file_exists($out) ? $out : dirname($out))) { + throw new Exception('Invalid or unwritable output file specified.'); + } + + $outMeta = $out . '.meta'; + $metadata = null; + if (!$force && is_file($outMeta)) { + $metadata = unserialize(file_get_contents($outMeta)); + } + + $output = $this->cachedCompile($metadata ? $metadata : $in); + + if (!$metadata || $metadata['updated'] != $output['updated']) { + $css = $output['compiled']; + unset($output['compiled']); + file_put_contents($out, $css); + file_put_contents($outMeta, serialize($output)); + } else { + $css = file_get_contents($out); + } + + return $css; + } + // compile only if changed input has changed or output doesn't exist public function checkedCompile($in, $out) { if (!is_file($out) || filemtime($in) > filemtime($out)) { diff --git a/tests/ServerTest.php b/tests/ServerTest.php new file mode 100644 index 00000000..3cf7237f --- /dev/null +++ b/tests/ServerTest.php @@ -0,0 +1,16 @@ +setImportDir(__DIR__ . '/inputs/test-imports/'); + $css = $server->checkedCachedCompile(__DIR__ . '/inputs/import.less', '/tmp/less.css'); + + $this->assertFileExists('/tmp/less.css'); + $this->assertFileExists('/tmp/less.css.meta'); + $this->assertEquals($css, file_get_contents('/tmp/less.css')); + $this->assertNotNull(unserialize(file_get_contents('/tmp/less.css.meta'))); + } +}