-
-
Notifications
You must be signed in to change notification settings - Fork 183
Expand file tree
/
Copy pathTimedPublishSubscriber.php
More file actions
78 lines (67 loc) · 2.58 KB
/
Copy pathTimedPublishSubscriber.php
File metadata and controls
78 lines (67 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
declare(strict_types=1);
namespace Bolt\Event\Subscriber;
use Bolt\Doctrine\TablePrefixTrait;
use Bolt\Entity\Content;
use Carbon\Carbon;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Types\Types;
use Doctrine\Persistence\ManagerRegistry;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Throwable;
class TimedPublishSubscriber implements EventSubscriberInterface
{
use TablePrefixTrait;
public const PRIORITY = 30;
private Connection $defaultConnection;
private string $tablePrefix;
public function __construct(
$tablePrefix,
ManagerRegistry $managerRegistry,
private LoggerInterface $logger
) {
/** @var Connection $connection */
$connection = $managerRegistry->getConnection('default');
$this->defaultConnection = $connection;
$this->tablePrefix = $this
->setTablePrefixes($tablePrefix, $managerRegistry)
->getTablePrefix($managerRegistry->getManager('default'));
}
/**
* Kernel request listener callback.
*/
public function onKernelRequest(): void
{
$conn = $this->defaultConnection;
$now = Carbon::now('UTC');
// Publish timed Content records when 'publish_at' has passed and Depublish published Content
// records when 'depublish_at' has passed. Note: Placeholders in DBAL don't work for tablenames.
$queryPublish = sprintf(
'update %scontent SET status = \'published\', published_at = :now WHERE status = \'timed\' AND published_at < :now',
$this->tablePrefix
);
$queryDepublish = sprintf(
'update %scontent SET status = \'held\', depublished_at = :now WHERE status = \'published\' AND depublished_at < :now',
$this->tablePrefix
);
try {
$conn->executeStatement($queryPublish, ['now' => $now], ['now' => Types::DATETIME_MUTABLE]);
$conn->executeStatement($queryDepublish, ['now' => $now], ['now' => Types::DATETIME_MUTABLE]);
} catch (Throwable $exception) {
// Fail silently for the user, but log at debug level for diagnostics.
$this->logger->debug('Failed to publish/depublish timed content', ['exception' => $exception]);
}
}
/**
* Return the events to subscribe to.
*/
public static function getSubscribedEvents(): array
{
return [
// Right after route is matched
KernelEvents::REQUEST => [['onKernelRequest', self::PRIORITY]],
];
}
}