Skip to content

Commit

Permalink
Minifier: Use Nette Caching for minified file content.
Browse files Browse the repository at this point in the history
  • Loading branch information
janbarasek authored Feb 5, 2021
1 parent b424b1b commit 21a94ae
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion src/Minifier/Minifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,42 @@
namespace Baraja\AssetsLoader\Minifier;


use Nette\Caching\Cache;
use Nette\Caching\Storage;

final class Minifier
{
/** @var AssetMinifier[] (format => service) */
private array $services = [];

private ?Cache $cache = null;

private string $cacheExpiration = '1 hour';


public function __construct(?Storage $storage = null)
{
if ($storage !== null) {
$this->cache = new Cache($storage, 'baraja-assets-loader-minifier');
}
}


public function minify(string $haystack, string $format): string
{
return $this->getMinifier($format)->minify($haystack);
$key = $format . '-' . md5($haystack);
if ($this->cache !== null && ($cache = $this->cache->load($key)) !== null) {
return (string) $cache;
}
$return = $this->getMinifier($format)->minify($haystack);
if ($this->cache !== null) {
$this->cache->save($key, $return, [
Cache::EXPIRE => $this->cacheExpiration,
Cache::TAGS => [$format, 'minifier'],
]);
}

return $return;
}


Expand Down Expand Up @@ -41,4 +68,10 @@ public function addMinifier(AssetMinifier $minifier, string $format): void

$this->services[$format] = $minifier;
}


public function setCacheExpiration(string $cacheExpiration): void
{
$this->cacheExpiration = $cacheExpiration;
}
}

0 comments on commit 21a94ae

Please sign in to comment.