Skip to content

Commit

Permalink
Add twig support to revalidate urls
Browse files Browse the repository at this point in the history
Closes #5
  • Loading branch information
Tam committed Feb 14, 2023
1 parent 5b5d1c1 commit 6f28fed
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 7 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.idea
.idea
.DS_Store
39 changes: 34 additions & 5 deletions src/jobs/RevalidateJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
namespace ether\utilitybelt\jobs;

use Craft;
use craft\elements\Entry;
use craft\queue\BaseJob;

class RevalidateJob extends BaseJob
{

public $sectionUid = null;
public $uris = [];

protected function defaultDescription (): string
Expand All @@ -18,23 +20,50 @@ protected function defaultDescription (): string
public function execute ($queue): bool
{
// Skip if localhost
if (str_contains(getenv('FRONTEND_URL'), 'local'))
return true;
// if (str_contains(getenv('FRONTEND_URL'), 'local'))
// return true;

$this->uris = array_unique($this->uris);

$client = Craft::createGuzzleClient();
$url = getenv('FRONTEND_URL') . '/api/revalidate?token=' . getenv('REVALIDATE_TOKEN') . '&path=/';
$total = count($this->uris);
$i = 0;
$section = null;

if (!empty($this->sectionUid))
{
$section = Craft::$app->getSections()->getSectionByUid($this->sectionUid);
$entriesInSection = Entry::find()->sectionId($section->id)->count();

$urisWithTemplates = 0;
foreach ($this->uris as $uri)
if (str_contains($uri, '{'))
$urisWithTemplates++;

$total = ($total - $urisWithTemplates) + ($entriesInSection * $urisWithTemplates);
}

foreach ($this->uris as $uri)
{
$client->get($url . ltrim($uri, '/'));
$queue->setProgress(++$i / $total * 100, $uri);
if (empty($this->sectionUid) || !str_contains($uri, '{')) {
$client->get($url . ltrim($uri, '/'));
$queue->setProgress(++$i / $total * 100, $uri);
} else {
foreach (Entry::find()->sectionId($section->id)->all() as $entry)
{
$parsedUrl = Craft::$app->getView()->renderObjectTemplate(
$uri,
$entry
);

$client->get($url . ltrim($parsedUrl, '/'));
$queue->setProgress(++$i / $total * 100, $uri);
}
}
}

return true;
}

}
}
3 changes: 2 additions & 1 deletion src/services/Revalidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ public function push (Element $element)
if ($element instanceof Entry)
{
$sectionUid = Craft::$app->getSections()->getSectionById($element->sectionId)->uid;
$job->sectionUid = $sectionUid;

foreach ($this->getAdditionalURIs($sectionUid) as $uri)
$job->uris[] = $uri;
Expand Down Expand Up @@ -272,4 +273,4 @@ private function updateJob (int $id, RevalidateJob $job)
->execute();
}

}
}

0 comments on commit 6f28fed

Please sign in to comment.