Created
October 14, 2015 22:13
-
-
Save fprochazka/1aa091d614ce9f982fce to your computer and use it in GitHub Desktop.
File filter for WebLoader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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]; | |
} | |
} | |
} |
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
Works like a charm :)