Skip to content

Commit

Permalink
Merge pull request ppy#11176 from nanaya/chat-filter-once
Browse files Browse the repository at this point in the history
Clean up chat filter function
  • Loading branch information
notbakaneko authored Apr 24, 2024
2 parents 0f7df7e + 9bcf6a3 commit ab6120f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 14 deletions.
8 changes: 1 addition & 7 deletions app/Models/Chat/Channel.php
Original file line number Diff line number Diff line change
Expand Up @@ -456,14 +456,8 @@ public function receiveMessage(User $sender, ?string $content, bool $isAction =
throw new API\ExcessiveChatMessagesException(osu_trans('api.error.chat.limit_exceeded'));
}

$chatFilters = app('chat-filters')->all();

foreach ($chatFilters as $filter) {
$content = str_replace($filter->match, $filter->replacement, $content);
}

$message = new Message([
'content' => $content,
'content' => app('chat-filters')->filter($content),
'is_action' => $isAction,
'timestamp' => $now,
]);
Expand Down
17 changes: 10 additions & 7 deletions app/Singletons/ChatFilters.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,22 @@

use App\Models\ChatFilter;
use App\Traits\Memoizes;
use Illuminate\Database\Eloquent\Collection;

class ChatFilters
{
use Memoizes;

public function all()
public function filter(string $text): string
{
return $this->memoize(__FUNCTION__, fn () => $this->fetch());
}
$replacements = $this->memoize(__FUNCTION__, function () {
$ret = [];
foreach (ChatFilter::all() as $entry) {
$ret[$entry->match] = $entry->replacement;
}

protected function fetch(): Collection
{
return ChatFilter::all();
return $ret;
});

return strtr($text, $replacements);
}
}

0 comments on commit ab6120f

Please sign in to comment.