<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Assetic\Asset\AssetCollection;
use Assetic\Asset\FileAsset;
use Minifier\MinFilter;
class AssetsWatchCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'assets:watch';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Watch and compile resource files.';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$minify = $this->option('minify');
//normally you should never target a specific environment, however it's entirely possible to access this same code branch by specifying minify on your vm or dev.
if (App::environment() == 'production')
{
$minify = true;
}
$sections = Config::get('assets');
$listeners = array();
foreach ($sections as $section => $assets)
{
foreach ($assets as $output => $input)
{
if (!is_string($output))
{
continue;
}
if (!is_array($input))
{
$input = array($input);
}
foreach ($input as $file)
{
$listeners[public_path().'/assets/'.$file][] = function() use ($output, $input, $file, $minify)
{
$filters = array();
if ($minify)
{
if (ends_with($output, '.js'))
{
$filters[] = new MinFilter('js');
}
if (ends_with($output, '.css'))
{
$filters[] = new MinFilter('css');
}
}
$collection = new AssetCollection(array(), $filters);
foreach ($input as $asset)
{
$collection->add(new FileAsset(public_path().'/assets/'.$asset));
}
$this->info('Detected change in '.$file.' compiling '.$output);
File::put(public_path().'/assets/'.$output, $collection->dump());
};
}
}
}
$watching = true;
$stats = array();
$listeners[app_path().'/config/asset.php'][] = function() use (&$watching)
{
$watching = false;
$this->info('Detected config change, exiting');
};
while ($watching)
{
foreach ($listeners as $file => $callbacks)
{
if (empty($stats[$file]))
{
$stats[$file] = md5(file_get_contents($file));
}
else
{
$md5 = md5(file_get_contents($file));
if ($stats[$file] !== $md5)
{
$stats[$file] = $md5;
foreach ($callbacks as $callback)
{
$callback();
}
}
}
}
usleep(500000);
}
}
protected function getOptions()
{
return array(
array('minify', 'm', InputOption::VALUE_NONE, 'Minify, defaults on in production.', null)
);
}
}