Skip to content

Instantly share code, notes, and snippets.

@RStankov
Created October 17, 2009 09:14
Show Gist options
  • Save RStankov/212303 to your computer and use it in GitHub Desktop.
Save RStankov/212303 to your computer and use it in GitHub Desktop.
<?php
require 'JSConcatinator.php';
// very basic usage example
header('Content-type: text/javascript; charset=UTF-8');
$concat = new JsConcatinator('javascripts');
echo $concat->concatinate('application.js');
<?php
class JsConcatinator {
private $path;
private $included;
public function __construct($path){
$this->path = rtrim($path, '/') . '/';
$this->included = array();
}
public function concatinate($file){
if (!$file = $this->pathToFile($file)) return '';
$content = file_get_contents($file) . "\n";
if (preg_match_all('/\/\/= require "(.*)"/', $content, $requirements)){
foreach($requirements[0] as $key => $match){
$content = str_replace($match, $this->concatinate($requirements[1][$key]), $content);
}
}
return $content;
}
private function pathToFile($file){
if (!$file) return false;
$file = $this->path . $file;
if (substr($file, -3) !== '.js'){
$file .= '.js';
}
if (in_array($file, $this->included)){
return false;
}
if (!file_exists($file)){
throw new Exception("{$file} not found");
}
return $this->included[] = $file;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment