Skip to content

Commit

Permalink
Merge branch '4.x' into develop
Browse files Browse the repository at this point in the history
# Conflicts:
#	CHANGELOG.md
#	composer.json
#	src/Blitz.php
#	src/templates/_utilities/diagnostics/_components/pages.twig
  • Loading branch information
bencroker committed Aug 4, 2024
2 parents 0982f8f + 8cfbad9 commit c25f42e
Show file tree
Hide file tree
Showing 19 changed files with 358 additions and 31 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@

## 5.6.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.
- Added the ability to track eager-loaded relation fields nested inside matrix blocks ([#657](https://github.com/putyourlightson/craft-blitz/issues/657)).
- Added a structure view to tracked nested element pages in the Blitz Diagnostics utility.

Expand Down
27 changes: 26 additions & 1 deletion src/Blitz.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use craft\elements\User;
use craft\enums\CmsEdition;
use craft\events\CancelableEvent;
use craft\events\DefineHtmlEvent;
use craft\events\DeleteElementEvent;
use craft\events\ElementEvent;
use craft\events\MoveElementEvent;
Expand Down Expand Up @@ -43,6 +44,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 @@ -117,7 +119,7 @@ public static function config(): array
/**
* @inheritdoc
*/
public string $schemaVersion = '5.5.0';
public string $schemaVersion = '5.6.0';

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

if (Craft::$app->edition === CmsEdition::Pro) {
Expand Down Expand Up @@ -578,6 +581,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 @@ -637,6 +656,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
15 changes: 4 additions & 11 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 @@ -111,7 +105,6 @@ public static function getPage(): ?array
{
$pageId = Craft::$app->getRequest()->getRequiredParam('pageId');
$page = CacheRecord::find()
->select(['id', 'uri'])
->where(['id' => $pageId])
->asArray()
->one();
Expand Down Expand Up @@ -222,7 +215,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 @@ -667,7 +660,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 @@ -77,6 +77,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 @@ -532,6 +532,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

0 comments on commit c25f42e

Please sign in to comment.