Skip to content

Commit

Permalink
Track changes in runtime extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
GromNaN committed Nov 27, 2023
1 parent 1b7a160 commit 1cf4df3
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/Extension/AttributeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
*
* @author Jérôme Tamarelle <[email protected]>
*/
final class AttributeExtension extends AbstractExtension
final class AttributeExtension extends AbstractExtension implements WithLastModified
{
private array $filters;
private array $functions;
Expand All @@ -41,6 +41,20 @@ public function __construct(
) {
}

public function getLastModified(): int
{
$lastModified = 0;

foreach ($this->objectsOrClasses as $objectOrClass) {
$r = new \ReflectionClass($objectOrClass);
if (is_file($r->getFileName()) && ($extensionTime = filemtime($r->getFileName())) > $lastModified) {
$lastModified = $extensionTime;
}
}

return $lastModified;
}

public function getFilters(): array
{
if (!isset($this->filters)) {
Expand Down
8 changes: 8 additions & 0 deletions src/Extension/WithLastModified.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Twig\Extension;

interface WithLastModified
{
public function getLastModified(): int;
}
4 changes: 4 additions & 0 deletions src/ExtensionSet.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Twig\Extension\ExtensionInterface;
use Twig\Extension\GlobalsInterface;
use Twig\Extension\StagingExtension;
use Twig\Extension\WithLastModified;
use Twig\Node\Expression\Binary\AbstractBinary;
use Twig\Node\Expression\Unary\AbstractUnary;
use Twig\NodeVisitor\NodeVisitorInterface;
Expand Down Expand Up @@ -115,6 +116,9 @@ public function getLastModified(): int
if (is_file($r->getFileName()) && ($extensionTime = filemtime($r->getFileName())) > $this->lastModified) {
$this->lastModified = $extensionTime;
}
if ($extension instanceof WithLastModified && ($extensionTime = $extension->getLastModified()) > $this->lastModified) {
$this->lastModified = $extensionTime;
}
}

return $this->lastModified;
Expand Down
6 changes: 6 additions & 0 deletions tests/Extension/AttributeExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,10 @@ public function testRuntimeExtension()
$this->assertSame([$class, 'fooFunction'], $extension->getFunctions()['foo']->getCallable());
$this->assertSame([$class, 'fooTest'], $extension->getTests()['foo']->getCallable());
}

public function testLastModified()
{
$extension = new AttributeExtension([ExtensionWithAttributes::class]);
$this->assertSame(filemtime(__DIR__ . '/Fixtures/ExtensionWithAttributes.php'), $extension->getLastModified());
}
}

0 comments on commit 1cf4df3

Please sign in to comment.