Skip to content

Commit

Permalink
Improve local caching
Browse files Browse the repository at this point in the history
  • Loading branch information
srenon committed Jul 4, 2020
1 parent 63c2f66 commit b8d85c2
Show file tree
Hide file tree
Showing 5 changed files with 133 additions and 24 deletions.
6 changes: 3 additions & 3 deletions Controller/Adminhtml/Version/Index.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,15 @@ public function __construct(
*/
public function execute()
{
$date = [
$data = [
'success' => 1,
'count' => $this->module->getUpdateCount()
'count' => $this->module->getCachedUpdateCount()
];

$result = $this->resultJsonFactory->create();
$result->setHeader('Cache-Control', 'max-age=302400', true);
$result->setHeader('Pragma', 'cache', true);
$result->setData($date);
$result->setData($data);
return $result;
}
}
142 changes: 124 additions & 18 deletions Model/Module.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use Exception;
use InvalidArgumentException;
use Magento\Backend\Model\Session;
use Magento\Framework\App\Cache\Type\Config;
use Magento\Framework\Component\ComponentRegistrar;
use Magento\Framework\Component\ComponentRegistrarInterface;
Expand All @@ -20,7 +21,7 @@ class Module
{
const URL = "https://updates.magepal.com/extensions.json";
const CACHE_KEY = 'magepal_extension_installed_list';
const DATA_VERSION = '1.0.1';
const DATA_VERSION = '1.0.2';
const LIFE_TIME = 604800;

/** @var int $updateCounter */
Expand All @@ -31,6 +32,7 @@ class Module
'MagePal_Core'
];

/** @var string */
private $filterModule = 'MagePal_';

private $composerJsonData = [];
Expand Down Expand Up @@ -59,69 +61,163 @@ class Module
* @var Config
*/
private $cache;
/**
* @var Session
*/
private $session;

private $timeStamp;

/**
* @param ModuleListInterface $moduleList
* @param ComponentRegistrarInterface $componentRegistrar
* @param ClientFactory $httpClientFactory
* @param ReadFactory $readFactory
* @param Config $cache
* @param Session $session
*/
public function __construct(
ModuleListInterface $moduleList,
ComponentRegistrarInterface $componentRegistrar,
ClientFactory $httpClientFactory,
ReadFactory $readFactory,
Config $cache
Config $cache,
Session $session
) {
$this->moduleList = $moduleList;
$this->componentRegistrar = $componentRegistrar;
$this->readFactory = $readFactory;
$this->httpClientFactory = $httpClientFactory;
$this->cache = $cache;
$this->session = $session;
}

/**
* @param string $needle
* @param array $haystack
* @param bool $defaultValue
* @return bool|mixed
*/
public function getArrayKeyIfExist($needle, $haystack, $defaultValue = false)
{
return array_key_exists($needle, $haystack) ? $haystack[$needle] : $defaultValue;
}

/**
* @return int
*/
public function getUpdateCount()
{
$this->getOutDatedExtension();
return $this->updateCounter;
}

/**
* @return int
*/
protected function getTimeStamp()
{
if (empty($this->timeStamp)) {
$this->timeStamp = strtotime("now");
}

return $this->timeStamp;
}

/**
* @return int
*/
protected function getTtl()
{
return $this->getTimeStamp() + 60 * 60 * 24;
}

/**
* @return int
*/
public function getCachedUpdateCount()
{
$now = $this->getTimeStamp();
$hash = $this->getHash();
$data = (array) $this->session->getData('magepal-core-notification-data');

if (empty($data) || !is_array($data)
|| $this->getArrayKeyIfExist('hash', $data, '') !== $hash
|| $now > (int) $this->getArrayKeyIfExist('ttl', $data, 0)
) {
$data = $this->setCountCache($this->getUpdateCount());
}

return (int) $data['count'] ?? 0;
}

/**
* @param $amount
* @return array
*/
protected function setCountCache($amount)
{
$data = [
'count' => $amount,
'hash' => $this->getHash(),
'ttl' => $this->getTtl()
];

$this->session->setData('magepal-core-notification-data', $data);
return $data;
}

/**
* @return string
*/
public function getHash()
{
return md5(json_encode($this->getPostData()));
}

/**
* @return array
*/
public function getOutDatedExtension()
{
if (empty($this->outDatedExtensionList)) {
if (!$data = $this->cache->load(self::CACHE_KEY)) {
$this->loadOutDatedExtension();
$data = $this->cache->load(self::CACHE_KEY);

try {
$dataObject = $data ? $this->decodeJson($data, true) : [];
} catch (Exception $e) {
$dataObject = [];
}

if (!$data
|| $this->getArrayKeyIfExist('data_version', $dataObject, 0) != self::DATA_VERSION
|| $this->getArrayKeyIfExist('hash', $dataObject, '') !== $this->getHash()
) {
$this->loadOutDatedExtensionCollection();
} else {
$dataObject = $this->decodeJson($data, true);

if (!array_key_exists('data_version', $dataObject)
|| $dataObject['data_version'] != self::DATA_VERSION) {
$this->loadOutDatedExtension();
} else {
if (array_key_exists('count', $dataObject)) {
$this->updateCounter = $dataObject['count'];
}
if (array_key_exists('count', $dataObject)) {
$this->updateCounter = $dataObject['count'];
}

if (array_key_exists('extensions', $dataObject)) {
$this->outDatedExtensionList = $dataObject['extensions'];
}
if (array_key_exists('extensions', $dataObject)) {
$this->outDatedExtensionList = $dataObject['extensions'];
}
}
}

return $this->outDatedExtensionList;
}

public function loadOutDatedExtension()
/**
* @return array
*/
public function loadOutDatedExtensionCollection()
{
try {
$extensionList = $this->getMyExtensionList();
$feed = $this->callApi(self::URL, $this->getPostData());
$latestVersions = $feed['extensions'] ?? [];
$hasUpdate = false;

foreach ($extensionList as $item) {
$item['latest_version'] = $item['install_version'];
Expand All @@ -138,16 +234,22 @@ public function loadOutDatedExtension()

if ($item['has_update']) {
$this->updateCounter += 1;
$hasUpdate = true;
}
}

$this->outDatedExtensionList[] = $item;
}

if ($hasUpdate) {
$this->setCountCache($this->updateCounter);
}

$dataObject = [
'count' => $this->updateCounter,
'extensions' => $this->outDatedExtensionList,
'data_version' => self::DATA_VERSION
'data_version' => self::DATA_VERSION,
'hash' => $this->getHash()
];

$this->cache->save(json_encode($dataObject), self::CACHE_KEY, [], self::LIFE_TIME);
Expand All @@ -158,6 +260,10 @@ public function loadOutDatedExtension()
return $this->outDatedExtensionList;
}

/**
* @param $moduleName
* @return string
*/
private function getTitleFromModuleName($moduleName)
{
$moduleName = str_replace($this->filterModule, '', $moduleName);
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

},
"type": "magento2-module",
"version": "1.1.2",
"version": "1.1.3",
"autoload": {
"files": [
"registration.php"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@
<div class="card">
<div class="headerline"><?= $block->escapeHtml($item['name'] ?? '') ?></div>
<div class="wrapper">
<div class="text-version"><?= $block->escapeHtml($item['latest_version'] ?? '') ?></div>
<div class="text-version">
<?= $block->escapeHtml($item['latest_version'] ?? '') ?>
</div>
</div>
</div>
<?php endif; ?>
Expand Down
3 changes: 2 additions & 1 deletion view/adminhtml/web/js/notification-icon.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ define([
$.ajax({
url: config.url,
type: 'get',
dataType: 'json'
dataType: 'json',
error: function (){}
}).done(function (response) {
if (typeof response === 'object' && response.hasOwnProperty('count') && response.count > 0) {
var html = '<span class="notifications-counter">' + response.count + '</span>';
Expand Down

0 comments on commit b8d85c2

Please sign in to comment.