Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sidebar panel to element edit pages #690

Merged
merged 14 commits into from
Aug 4, 2024
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
# Release Notes for Blitz

## 4.22.0 - Unreleased

> [!NOTE]
> For the cache and expiry dates to appear in the new sidebar panel, the cache should be cleared or refreshed after this update completes.

### Added

- Added a sidebar panel to element edit pages ([#690](https://github.com/putyourlightson/craft-blitz/issues/690)).
- Added a `dateCached` column to cache records which is output in the sidebar panel and the Blitz Diagnostics utility.

### Changed

- Blitz now requires Craft CMS 4.5.0 or later.

## 4.21.0 - 2024-07-24

### Added
Expand Down
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "putyourlightson/craft-blitz",
"description": "Intelligent static page caching for creating lightning-fast sites.",
"version": "4.21.0",
"version": "4.22.0",
"type": "craft-plugin",
"homepage": "https://putyourlightson.com/plugins/blitz",
"license": "proprietary",
Expand All @@ -17,7 +17,7 @@
"php": "^8.0.2",
"amphp/http-client": "^4.0",
"amphp/parallel": "^1.0",
"craftcms/cms": "^4.4.8",
"craftcms/cms": "^4.5.0",
"cypresslab/gitelephant": "^4.0",
"putyourlightson/craft-blitz-hints": "^1.2.2",
"putyourlightson/craft-sprig-core": "^2.7.3"
Expand Down
27 changes: 26 additions & 1 deletion src/Blitz.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use craft\base\Plugin;
use craft\elements\User;
use craft\events\BatchElementActionEvent;
use craft\events\DefineHtmlEvent;
use craft\events\DeleteElementEvent;
use craft\events\ElementEvent;
use craft\events\MoveElementEvent;
Expand Down Expand Up @@ -40,6 +41,7 @@
use putyourlightson\blitz\drivers\generators\BaseCacheGenerator;
use putyourlightson\blitz\drivers\purgers\BaseCachePurger;
use putyourlightson\blitz\drivers\storage\BaseCacheStorage;
use putyourlightson\blitz\helpers\ElementSidebarHelper;
use putyourlightson\blitz\helpers\IntegrationHelper;
use putyourlightson\blitz\helpers\RefreshCacheHelper;
use putyourlightson\blitz\models\RefreshDataModel;
Expand Down Expand Up @@ -111,7 +113,7 @@ public static function config(): array
/**
* @inheritdoc
*/
public string $schemaVersion = '4.13.0';
public string $schemaVersion = '4.22.0';

/**
* @inheritdoc
Expand Down Expand Up @@ -153,6 +155,7 @@ public function init(): void
$this->registerCpUrlRules();
$this->registerUtilities();
$this->registerWidgets();
$this->registerSidebarPanels();
$this->registerRedirectAfterInstall();

if (Craft::$app->getEdition() === Craft::Pro) {
Expand Down Expand Up @@ -549,6 +552,22 @@ function(RegisterComponentTypesEvent $event) {
);
}

/**
* Registers sidebar panels
*
* @since 4.22.0
*/
private function registerSidebarPanels(): void
{
Event::on(Element::class, Element::EVENT_DEFINE_SIDEBAR_HTML,
function(DefineHtmlEvent $event) {
/** @var Element $element */
$element = $event->sender;
$event->html .= ElementSidebarHelper::getSidebarHtml($element);
},
);
}

/**
* Registers redirect after install
*/
Expand Down Expand Up @@ -608,6 +627,12 @@ function(RegisterUserPermissionsEvent $event) {
'blitz:refresh-tagged' => [
'label' => Craft::t('blitz', 'Refresh tagged cache'),
],
'blitz:refresh-page' => [
'label' => Craft::t('blitz', 'Refresh pages via the sidebar panel and diagnostics utility'),
],
'blitz:view-sidebar-panel' => [
'label' => Craft::t('blitz', 'View sidebar panel on element edit pages'),
],
],
];
}
Expand Down
22 changes: 20 additions & 2 deletions src/controllers/CacheController.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use craft\web\Controller;
use craft\web\View;
use putyourlightson\blitz\Blitz;
use putyourlightson\blitz\models\SiteUriModel;
use yii\web\ForbiddenHttpException;
use yii\web\Response;

Expand Down Expand Up @@ -42,8 +43,8 @@ public function beforeAction($action): bool

$request = Craft::$app->getRequest();

// Require permission if posted from utility
if ($request->getIsPost() && $request->getParam('utility')) {
// Require permission if posted from the CP
if ($request->getIsPost() && $request->getIsCpRequest()) {
$this->requirePermission('blitz:' . $action->id);
} else {
// Verify API key
Expand Down Expand Up @@ -209,6 +210,23 @@ public function actionRefreshTagged(): ?Response
return $this->getSuccessResponse('Tagged cache successfully refreshed.');
}

/**
* Refreshes a cached page, forcing a clear. Used by the element sidebar panel and diagnostics utility.
*/
public function actionRefreshPage(): ?Response
{
$siteId = Craft::$app->getRequest()->getRequiredParam('siteId');
$uri = Craft::$app->getRequest()->getRequiredParam('uri');
$siteUri = new SiteUriModel([
'siteId' => $siteId,
'uri' => $uri,
]);

Blitz::$plugin->refreshCache->refreshSiteUris([$siteUri], [], true);

return $this->getSuccessResponse('Cached page successfully refreshed.');
}

/**
* Returns a success response.
*/
Expand Down
2 changes: 2 additions & 0 deletions src/controllers/DiagnosticsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ public function actionExportPages(int $siteId, ?int $elementId = null, ?int $que
'elements' => $page['elementCount'] ?: 0,
'elementQueries' => $page['elementQueryCount'] ?: 0,
'tags' => $page['tagCount'] ?: 0,
'dateCached' => $page['dateCached'],
'expiryDate' => $page['expiryDate'],
];
}
Expand Down Expand Up @@ -104,6 +105,7 @@ public function actionExportIncludes(int $siteId): Response
'params' => $include['params'],
'elements' => $include['elementCount'] ?: 0,
'elementQueries' => $include['elementQueryCount'] ?: 0,
'dateCached' => $include['dateCached'],
'expiryDate' => $include['expiryDate'],
];
}
Expand Down
14 changes: 4 additions & 10 deletions src/helpers/DiagnosticsHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,18 +63,12 @@ public static function getSiteId(): ?int

public static function getPagesCount(int $siteId): int
{
return CacheRecord::find()
->where(['siteId' => $siteId])
->andWhere(['not', self::IS_CACHED_INCLUDE_CONDITION])
->count();
return self::getPagesQuery($siteId)->count();
}

public static function getIncludesCount(int $siteId): int
{
return CacheRecord::find()
->where(['siteId' => $siteId])
->andWhere(self::IS_CACHED_INCLUDE_CONDITION)
->count();
return self::getIncludesQuery($siteId)->count();
}

public static function getParamsCount(int $siteId): int
Expand Down Expand Up @@ -218,7 +212,7 @@ public static function getIncludesQuery(int $siteId): ActiveQuery
$index = self::getIncludesIndexColumnForSelect();

return self::getBasePagesQuery($siteId)
->select(['caches.id', 'uri', $index . ' AS index', 'template', 'params', 'elementCount', 'elementQueryCount', 'expiryDate'])
->select(['caches.id', 'caches.siteId', 'uri', $index . ' AS index', 'template', 'params', 'elementCount', 'elementQueryCount', 'dateCached', 'expiryDate'])
->innerJoin([
'indexes' => IncludeRecord::find()
->where(['siteId' => $siteId]),
Expand Down Expand Up @@ -642,7 +636,7 @@ private static function getBasePagesQuery(int $siteId, ?int $elementId = null, ?
{
$query = CacheRecord::find()
->from(['caches' => CacheRecord::tableName()])
->select(['id', 'uri', 'elementCount', 'elementQueryCount', 'tagCount', 'expiryDate'])
->select(['id', 'siteId', 'uri', 'elementCount', 'elementQueryCount', 'tagCount', 'dateCached', 'expiryDate'])
->leftJoin([
'elements' => ElementCacheRecord::find()
->select(['cacheId', 'count(*) as elementCount'])
Expand Down
90 changes: 90 additions & 0 deletions src/helpers/ElementSidebarHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php
/**
* @copyright Copyright (c) PutYourLightsOn
*/

namespace putyourlightson\blitz\helpers;

use Craft;
use craft\base\Element;
use craft\base\Event;
use craft\events\DefineElementEditorHtmlEvent;
use craft\helpers\Db;
use craft\helpers\Html;
use craft\helpers\UrlHelper;
use putyourlightson\blitz\Blitz;
use putyourlightson\blitz\models\SiteUriModel;
use putyourlightson\blitz\records\CacheRecord;

class ElementSidebarHelper
{
/**
* @event DefineHtmlEvent
*/
public const EVENT_DEFINE_SIDEBAR_HTML = 'defineSidebarHtml';

/**
* @event DefineHtmlEvent
*/
public const EVENT_DEFINE_META_FIELDS_HTML = 'defineMetaFieldsHtml';

/**
* Returns the HTML for the sidebar.
*/
public static function getSidebarHtml(Element $element): string
{
if (Blitz::$plugin->settings->cachingEnabled === false) {
return '';
}

$uri = $element->uri;
if ($uri === null) {
return '';
}

$html = Html::beginTag('fieldset', ['class' => 'blitz-element-sidebar']) .
Html::tag('legend', 'Blitz', ['class' => 'h6']) .
Html::tag('div', self::metaFieldsHtml($element), ['class' => 'meta']) .
Html::endTag('fieldset');

$event = new DefineElementEditorHtmlEvent([
'element' => $element,
'html' => $html,
]);
Event::trigger(self::class, self::EVENT_DEFINE_SIDEBAR_HTML, $event);

return $event->html;
}

private static function metaFieldsHtml(Element $element): string
{
$siteUri = new SiteUriModel([
'siteId' => $element->siteId,
'uri' => $element->uri,
]);
$cachedValue = Blitz::$plugin->cacheStorage->get($siteUri);

/** @var CacheRecord|null $cacheRecord */
$cacheRecord = CacheRecord::find()
->where($siteUri->toArray())
->one();

$html = Craft::$app->getView()->renderTemplate('blitz/_element-sidebar', [
'cached' => !empty($cachedValue),
'expired' => $cacheRecord && $cacheRecord->expiryDate && $cacheRecord->expiryDate <= Db::prepareDateForDb('now'),
'isCacheable' => Blitz::$plugin->cacheRequest->getIsCacheableSiteUri($siteUri),
'pageId' => $cacheRecord->id,
'dateCached' => $cacheRecord->dateCached ?? null,
'expiryDate' => $cacheRecord->expiryDate ?? null,
'refreshActionUrl' => UrlHelper::actionUrl('blitz/cache/refresh-page', $siteUri->toArray()),
]);

$event = new DefineElementEditorHtmlEvent([
'element' => $element,
'html' => $html,
]);
Event::trigger(self::class, self::EVENT_DEFINE_META_FIELDS_HTML, $event);

return $event->html;
}
}
1 change: 1 addition & 0 deletions src/migrations/Install.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ protected function createTables(): bool
'siteId' => $this->integer()->notNull(),
'uri' => $this->string(Blitz::$plugin->settings->maxUriLength)->notNull(),
'paginate' => $this->integer(),
'dateCached' => $this->dateTime(),
'expiryDate' => $this->dateTime(),
]);
}
Expand Down
31 changes: 31 additions & 0 deletions src/migrations/m240731_120000_add_datecached_column.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace putyourlightson\blitz\migrations;

use craft\db\Migration;
use putyourlightson\blitz\records\CacheRecord;

class m240731_120000_add_datecached_column extends Migration
{
/**
* @inheritdoc
*/
public function safeUp(): bool
{
if (!$this->db->columnExists(CacheRecord::tableName(), 'dateCached')) {
$this->addColumn(CacheRecord::tableName(), 'dateCached', $this->dateTime()->after('paginate'));
}

return true;
}

/**
* @inheritdoc
*/
public function safeDown(): bool
{
echo self::class . " cannot be reverted.\n";

return true;
}
}
1 change: 1 addition & 0 deletions src/records/CacheRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* @property int $siteId
* @property string $uri
* @property int|null $paginate
* @property DateTime|null $dateCached
* @property DateTime|null $expiryDate
* @property-read ElementCacheRecord[] $elements
*/
Expand Down
1 change: 1 addition & 0 deletions src/services/GenerateCacheService.php
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,7 @@ public function save(string $content, SiteUriModel $siteUri): ?string

$cacheValue = array_merge($cacheValue, [
'paginate' => $paginate,
'dateCached' => Db::prepareDateForDb('now'),
'expiryDate' => Db::prepareDateForDb($this->options->expiryDate),
]);

Expand Down
Loading