Skip to content

Instantly share code, notes, and snippets.

@wtnabe
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wtnabe/6d09c219cf3a1bc1eec8 to your computer and use it in GitHub Desktop.
Save wtnabe/6d09c219cf3a1bc1eec8 to your computer and use it in GitHub Desktop.
asset helper for limonade-php
<html>
<head>
<?= javascript_include_tag(); ?>
<?= stylesheet_include_tag(); ?>
</head>
<body>
<p>body</p>
</body>
</html>
<?php
class Limonade_Simple_Assets {
/**
* @var array
*/
var $ext = array('stylesheet' => 'css', 'javascript' => 'js');
/**
* @var array
*/
var $paths = array('lib', '');
static function include_tag($name) {
$self = new Limonade_Simple_Assets();
$tag_method = "{$name}_tag";
$assets = array();
if ( option('env') == ENV_PRODUCTION ) {
return $self->{$tag_method}("application.{$self->ext[$name]}", true);
} else {
$assets = array();
foreach ( $self->paths as $basedir ) {
$asset_dir = option('public_dir')."/{$name}s";
$assets = $assets + $self->shallow_glob($name, $asset_dir, $basedir);
}
return join("\n", array_map(array($self, $tag_method), $assets));
}
}
/**
* @param string $name
* @param string $path
* @param string $basedir
* @return array
*/
function shallow_glob($name, $path, $basedir) {
if ( file_exists($path) ) {
$cwd = getcwd();
chdir($path);
$assets = glob(join('/', array_filter(array($basedir, "*.{$this->ext[$name]}"))));
chdir($cwd);
}
return $assets;
}
/**
* @param string $name
* @return string
*/
function combined_file($name, $production = false) {
$path = '';
if ( $production ) {
$cwd = getcwd();
chdir("{$name}s");
$glob = glob("application.*\.{$this->ext[$name]}");
if ( sizeof($glob) > 0 ) {
$path = reset($glob);
}
chdir($cwd);
}
return $path;
}
/**
* @param string $js
* @param boolean $productiokn
* @return string
*/
function javascript_tag($js, $production = false) {
if ( preg_match('/^application\.([^.]+\.)?js$/', $js) or $production ) {
$js = $this->combined_file('javascript', $production);
}
return ($js)
? '<script type="text/javascript" src="'.url_for("/javascripts/{$js}").'"></script>'
: '';
}
/**
* @param string $css
* @param boolean $production
* @return string
*/
function stylesheet_tag($css, $production = false) {
if ( preg_match('/^application\.([^.]+\.)?css$/', $css ) ) {
if ( $production ) {
$css = $this->combined_file('stylesheet', $production);
} else {
return '';
}
}
return '<link rel="stylesheet" href="'.url_for("/stylesheets/{$css}").'">';
}
}
/**
* @return html
*/
function javascript_include_tag() {
return Limonade_Simple_Assets::include_tag('javascript');
}
/**
* @return html
*/
function stylesheet_include_tag() {
return Limonade_Simple_Assets::include_tag('stylesheet');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment