Skip to content

Commit

Permalink
perf: store censors in cache rather than db
Browse files Browse the repository at this point in the history
  • Loading branch information
imorland committed Jun 12, 2024
1 parent a6b6ce5 commit 719a409
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
15 changes: 13 additions & 2 deletions src/Listener/AddCensorChecks.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,26 @@

use Flarum\Settings\Event\Saving;
use FoF\Filter\CensorGenerator;
use Illuminate\Contracts\Cache\Store as Cache;

class AddCensorChecks
{
/**
* @var Cache
*/
protected $cache;

public function __construct(Cache $cache)
{
$this->cache = $cache;
}

public function handle(Saving $event)
{
if (isset($event->settings['fof-filter.words'])) {
$event->settings['fof-filter.censors'] = json_encode(
$this->cache->forever('fof-filter.censors', json_encode(
CensorGenerator::generateCensors($event->settings['fof-filter.words'])
);
));
}
}
}
13 changes: 10 additions & 3 deletions src/Listener/CheckPost.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Flarum\User\Guest;
use FoF\Filter\CensorGenerator;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Cache\Store as Cache;
use Illuminate\Mail\Mailer;
use Illuminate\Mail\Message;
use Symfony\Contracts\Translation\TranslatorInterface;
Expand All @@ -46,12 +47,18 @@ class CheckPost
*/
protected $bus;

public function __construct(SettingsRepositoryInterface $settings, TranslatorInterface $translator, Mailer $mailer, Dispatcher $bus)
/**
* @var Cache
*/
protected $cache;

public function __construct(SettingsRepositoryInterface $settings, TranslatorInterface $translator, Mailer $mailer, Dispatcher $bus, Cache $cache)
{
$this->settings = $settings;
$this->translator = $translator;
$this->mailer = $mailer;
$this->bus = $bus;
$this->cache = $cache;
}

public function handle(Saving $event)
Expand Down Expand Up @@ -98,13 +105,13 @@ function ($matches) use (&$isExplicit) {

protected function getCensors(): array
{
$censors = json_decode($this->settings->get('fof-filter.censors'), true);
$censors = json_decode($this->cache->get('fof-filter.censors'), true);

// Ensure $censors is a non-empty array
if (!is_array($censors) || empty($censors)) {
// Censors have not been initialized correctly, generate them
$censors = CensorGenerator::generateCensors($this->settings->get('fof-filter.words'));
$this->settings->set('fof-filter.censors', json_encode($censors));
$this->cache->forever('fof-filter.censors', json_encode($censors));
}

return $censors;
Expand Down

0 comments on commit 719a409

Please sign in to comment.