Skip to content

Commit

Permalink
Implementing singleton pattern for ViewCache
Browse files Browse the repository at this point in the history
  • Loading branch information
Vahram1995 committed Nov 27, 2024
1 parent f230881 commit 393bfad
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 37 deletions.
13 changes: 7 additions & 6 deletions src/Console/Commands/ResourceCacheClearCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,13 @@ class ResourceCacheClearCommand extends QtCommand
* Command description
* @var string
*/
protected $description = 'Clearing resource caches';
protected $description = 'Clears resource cache';

/**
* Command help text
* @var string
*/
protected $help = 'The command will clear the resource caches.';
protected $help = 'The command will clear the resource cache';

/**
* Command options
Expand Down Expand Up @@ -133,7 +133,7 @@ private function importModules()
config()->import(new Setup('config', 'modules'));
}

if (config()->has('modules')){
if (config()->has('modules') && is_array(config()->get('modules.modules'))){
$this->modules = array_keys(array_change_key_case(config()->get('modules.modules')));
}
} catch (ConfigException|DiException|ReflectionException $e) {
Expand Down Expand Up @@ -211,6 +211,7 @@ private function clearResourceModuleAndType(?string $moduleName = null, ?string
if (!$type) {
$dir = $dir . DS . '*';
}

$dir = $dir . DS . strtolower($moduleName);
}

Expand All @@ -223,14 +224,14 @@ private function clearResourceModuleAndType(?string $moduleName = null, ?string
*/
private function removeFilesFromDirectory(string $dir): void
{
$entries = $this->fs->glob($dir . DIRECTORY_SEPARATOR . '*');
$entries = $this->fs->glob($dir . DS . '*');

foreach ($entries as $entry) {
if ($this->fs->isDirectory($entry)) {
$this->removeFilesFromDirectory($entry);

if (basename($entry) !== config()->get('view_cache.cache_dir', 'cache') &&
count($this->fs->glob($entry . DIRECTORY_SEPARATOR . '*')) === 0
if ($this->fs->fileName($entry) !== config()->get('view_cache.cache_dir', 'cache') &&
count($this->fs->glob($entry . DS . '*')) === 0
) {
$this->fs->removeDirectory($entry);
}
Expand Down
75 changes: 48 additions & 27 deletions src/Libraries/ResourceCache/ViewCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
namespace Quantum\Libraries\ResourceCache;

use Quantum\Libraries\Storage\FileSystem;
use Quantum\Exceptions\ConfigException;
use Quantum\Exceptions\DiException;
use ReflectionException;
use voku\helper\HtmlMin;
use Quantum\Di\Di;
use Exception;

class ViewCache
{
Expand All @@ -24,31 +24,39 @@ class ViewCache
/**
* @var object
*/
private static $fs;
private $fs;

/**
* @var ViewCache
*/
private static $instance = null;

public static function getInstance(): ViewCache
{
if (self::$instance === null) {
self::$instance = new self();
}

return self::$instance;
}

/**
* @param bool $fromCommand
* @throws ConfigException
* @throws DiException
* @throws ReflectionException
* @throws Exception
*/
public function __construct(bool $fromCommand = false)
public function __construct()
{
self::$fs = Di::get(FileSystem::class);
$this->fs = Di::get(FileSystem::class);

if (!config()->has('view_cache') && !$fromCommand) {
throw ConfigException::configCollision('view_cache');
if (!config()->has('view_cache')) {
throw new Exception('The config "view_cache" does not exists.');
}

$configCacheDir = config()->get('view_cache.cache_dir', 'cache');

$this->cacheDir = base_dir() . DS . $configCacheDir . DS . 'views' . DS;
$this->cacheDir = self::getCacheDir();

if ($module = current_module()) {
$this->cacheDir = base_dir() . DS . $configCacheDir . DS . 'views' . DS . strtolower($module) . DS;
}

if (!self::$fs->isDirectory($this->cacheDir) && !$fromCommand) {
if (!$this->fs->isDirectory($this->cacheDir)) {
mkdir($this->cacheDir, 0777, true);
}
}
Expand All @@ -66,7 +74,7 @@ public function set(string $key, string $content, string $sessionId): ViewCache
}

$cacheFile = $this->getCacheFile($key, $sessionId);
self::$fs->put($cacheFile, $content);
$this->fs->put($cacheFile, $content);

return $this;
}
Expand All @@ -80,13 +88,13 @@ public function set(string $key, string $content, string $sessionId): ViewCache
public function get(string $key, string $sessionId, int $ttl): ?string
{
$cacheFile = $this->getCacheFile($key, $sessionId);
if (!self::$fs->exists($cacheFile)) {
if (!$this->fs->exists($cacheFile)) {
return null;
}

$data = self::$fs->get($cacheFile);
if (time() > (self::$fs->lastModified($cacheFile) + $ttl)) {
self::$fs->remove($cacheFile);
$data = $this->fs->get($cacheFile);
if (time() > ($this->fs->lastModified($cacheFile) + $ttl)) {
$this->fs->remove($cacheFile);
return null;
}

Expand All @@ -101,8 +109,8 @@ public function get(string $key, string $sessionId, int $ttl): ?string
public function delete(string $key, string $sessionId): void
{
$cacheFile = $this->getCacheFile($key, $sessionId);
if (self::$fs->exists($cacheFile)) {
self::$fs->remove($cacheFile);
if ($this->fs->exists($cacheFile)) {
$this->fs->remove($cacheFile);
}
}

Expand All @@ -112,22 +120,35 @@ public function delete(string $key, string $sessionId): void
* @param int $ttl
* @return bool
*/
public static function exists(string $key, string $sessionId, int $ttl): bool
public function exists(string $key, string $sessionId, int $ttl): bool
{
$cacheFile = (new self())->getCacheFile($key, $sessionId);
$cacheFile = $this->getCacheFile($key, $sessionId);

if (!self::$fs->exists($cacheFile)) {
if (!$this->fs->exists($cacheFile)) {
return false;
}

if (time() > (self::$fs->lastModified($cacheFile) + $ttl)) {
self::$fs->remove($cacheFile);
if (time() > ($this->fs->lastModified($cacheFile) + $ttl)) {
$this->fs->remove($cacheFile);
return false;
}

return true;
}

private static function getCacheDir(): string
{
$configCacheDir = config()->get('view_cache.cache_dir', 'cache');

$cacheDir = base_dir() . DS . $configCacheDir . DS . 'views' . DS;

if ($module = current_module()) {
$cacheDir = base_dir() . DS . $configCacheDir . DS . 'views' . DS . strtolower($module) . DS;
}

return $cacheDir;
}

/**
* @param string $key
* @param string $sessionId
Expand Down
4 changes: 2 additions & 2 deletions src/Mvc/MvcManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,10 @@ public static function handle(Request $request, Response $response)

if ($cacheSettings &&
session()->getId() &&
ViewCache::exists(route_uri(), session()->getId(), $cacheSettings['ttl'])
ViewCache::getInstance()->exists(route_uri(), session()->getId(), $cacheSettings['ttl'])
){
call_user_func_array(function () use (&$response, $cacheSettings) {
$content = (new ViewCache())->get(route_uri(), session()->getId(), $cacheSettings['ttl']);
$content = ViewCache::getInstance()->get(route_uri(), session()->getId(), $cacheSettings['ttl']);
$response->html($content);
}, []);

Expand Down
2 changes: 1 addition & 1 deletion src/Mvc/QtView.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ public function render(string $view, array $params = []): ?string
$content = $this->renderFile($this->layout);

if (($cacheSettings = route_cache_settings()) && session()->getId()){
$content = (new ViewCache())
$content = ViewCache::getInstance()
->set(route_uri(), $content, session()->getId())
->get(route_uri(), session()->getId(), $cacheSettings['ttl']);
}
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/Libraries/ResourceCache/ViewCacheTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public function setUp():void
config()->import(new Setup('config', 'view_cache'));
}
config()->set('resource_cache', true);
$this->viewCache = new ViewCache();
$this->viewCache = ViewCache::getInstance();
}

public function testStoreViewCache()
Expand Down

0 comments on commit 393bfad

Please sign in to comment.