Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fprochazka
Created October 14, 2015 22:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fprochazka/1aa091d614ce9f982fce to your computer and use it in GitHub Desktop.
Save fprochazka/1aa091d614ce9f982fce to your computer and use it in GitHub Desktop.
File filter for WebLoader
<?php
namespace WebLoader;
use Kdyby;
use Nette;
use Nette\Utils\FileSystem;
use Nette\Utils\Strings;
use WebLoader\Compiler;
/**
* @author Filip Procházka <filip@prochazka.su>
*/
class AssetsPublishingCssFilter
{
/**
* @var Compiler
*/
private $compiler;
/**
* @var string
*/
private $sourceFile;
/**
* @var array
*/
private $publishedFiles = [];
/**
* @var string
*/
private $publicPath;
public function __construct($publicPath, Nette\Http\IRequest $httpRequest)
{
$this->publicPath = rtrim($httpRequest->getUrl()->basePath, '/') . '/' . $publicPath;
}
/**
* @param string $code
* @param Compiler $compiler
* @param string $file
* @return string
*/
public function __invoke($code, Compiler $compiler, $file)
{
$this->compiler = $compiler;
$this->sourceFile = $file;
$processor = function ($match) {
return sprintf("url('%s')", $this->copyAsset($match['path']));
};
$code = Strings::replace($code, '~url\\(("|\')(?P<path>[^"\'\\)]+)(\1)\\)~i', $processor);
$code = Strings::replace($code, '~url\\((?P<path>[^"\'\\)]+)\\)~i', $processor);
return $code;
}
private function copyAsset($source)
{
$relativeSourceDir = realpath(dirname($this->sourceFile)) . DIRECTORY_SEPARATOR;
list($sourceFile, $suffix) = self::splitSuffix($source);
if (!$originalFile = realpath($sourceFile[0] !== '/' ? ($relativeSourceDir . $sourceFile) : $sourceFile)) {
return $source;
}
if (!isset($this->publishedFiles[$originalFile])) {
$outputDir = $this->compiler->getOutputDir();
$outputSubDir = substr(md5(dirname($originalFile)), 0, 10);
$targetFile = $outputDir . '/' . $outputSubDir . '/' . basename($originalFile);
$publicFile = $this->publicPath . '/' . $outputSubDir . '/' . basename($targetFile);
if (!file_exists($targetFile) || filemtime($originalFile) > filemtime($targetFile)) {
FileSystem::copy($originalFile, $targetFile);
}
$this->publishedFiles[$originalFile] = $publicFile;
}
return $this->publishedFiles[$originalFile] . $suffix;
}
private static function splitSuffix($source)
{
if ($m = Strings::match($source, '~^(?P<file>[^\?\#]+)(?P<suffix>[\?\#].+)\\z~')) {
return [$m['file'], $m['suffix']];
} else {
return [$source, NULL];
}
}
}
@fprochazka
Copy link
Author

Works like a charm :)


snimek obrazovky porizeny 2015-10-15 00 19 17


snimek obrazovky porizeny 2015-10-15 00 22 06

@EdaCZ
Copy link

EdaCZ commented Oct 16, 2015

Nice :-)

Why you use copying instead of symlinks?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment