emielburgman / symfony-comments
The shared half of a blog comment system for Symfony: the Doctrine columns as a trait, a comment form type, two interchangeable spam guards (session maths captcha or stateless honeypot + signed time trap), a posted event and avatar Twig helpers.
Package info
bitbucket.org/emielburgman/symfony-comments
Type:symfony-bundle
pkg:composer/emielburgman/symfony-comments
Requires
- php: >=8.2
- doctrine/orm: ^2.15|^3.0
- psr/clock: ^1.0
- psr/event-dispatcher: ^1.0
- symfony/config: ^6.4|^7.0
- symfony/dependency-injection: ^6.4|^7.0
- symfony/form: ^6.4|^7.0
- symfony/http-foundation: ^6.4|^7.0
- symfony/http-kernel: ^6.4|^7.0
- symfony/validator: ^6.4|^7.0
Requires (Dev)
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ^2.1
- phpstan/phpstan-doctrine: ^2.0
- phpunit/phpunit: ^10.5|^11.0|^12.0
- symfony/cache: ^6.4|^7.0
- symfony/event-dispatcher: ^6.4|^7.0
- twig/twig: ^3.0
Suggests
- twig/twig: Exposes comment_initials(), comment_avatar_index() and gravatar_url() to templates.
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-17 16:50:15 UTC
README
The shared half of a blog comment system: the Doctrine columns as a trait, a comment form type, two interchangeable spam guards, a "comment posted" event and the avatar helpers. Everything the consuming apps disagree about stays in the apps.
MIT. Symfony 6.4 and 7.x, PHP 8.2+.
Why this exists
The comment system started as application code in one app. When a second app
wanted comments on its blog, the choice was a copy or a package — and the
sibling symfony-visit-storage
README already documents what copying does: at three copies the signatures, the
defaults and even a flag's polarity had drifted, and none of it was a decision.
So the second user gets the package, not a copy.
The two apps disagree in four ways, and the package is shaped around leaving each of them open:
| App A | App B | So the package… | |
|---|---|---|---|
| What a comment hangs off | two Doctrine relations (post, project) | a static post registry, no entity | ships columns as a trait, no entity |
| Spam | session maths captcha | deliberately stateless — no session at all | ships both guards, chosen in config |
| Notification | its own Telegram HTTP client | Symfony Notifier | dispatches an event, sends nothing |
| Front end | Tailwind 3 + Stimulus | Tailwind 4 + Alpine | ships no CSS and no templates |
What is deliberately not here
- The entity and its subject relation. Each app declares its own
Commentanduses the trait for the four shared columns. - Indexes. They index the subject relation, which the package does not know.
- Migrations. Adopting the trait changes no schema — see below.
- The admin screen, templates and form theme. Two design systems.
- The notification transport. Listen to
CommentPostedEventand send it however your app already sends things. - On/off switches. One app has a site-wide setting plus a per-post flag, the other a feature flag. Decide in the app whether to render the form at all.
- Rate limiting. Use
symfony/rate-limiterin the controller; a guard judges one submission, a limiter judges a client's cadence.
Install
composer require emielburgman/symfony-comments
// config/bundles.php
Emielburgman\Comments\CommentsBundle::class => ['all' => true],
# config/packages/comments.yaml — every key is optional
comments:
comment_class: App\Entity\Comment # CommentType's default data_class
spam_guard: math_captcha # or: stateless
math_captcha:
max_pending: 20 # pending answers kept per session
session_key: captcha_answers
error_message: 'Incorrect captcha answer.'
stateless:
secret: '%kernel.secret%'
min_seconds: 3
max_age_seconds: 86400
max_links: 2
pow_difficulty: 0 # 0 = off; see "Proof of work"
error_message: 'Your comment could not be posted. Please try again.'
The entity
use Emielburgman\Comments\Mapping\CommentFields;
#[ORM\Entity(repositoryClass: CommentRepository::class)]
#[ORM\HasLifecycleCallbacks] // required — see below
#[ORM\Index(name: 'idx_comment_post_created', columns: ['blog_post_id', 'created_at'])]
class Comment
{
use CommentFields; // author, email, content, created_at
#[ORM\Id, ORM\GeneratedValue, ORM\Column]
private ?int $id = null;
#[ORM\ManyToOne(inversedBy: 'comments')]
private ?BlogPost $blogPost = null; // your subject, your relation
}
The columns are author VARCHAR(255), email VARCHAR(255), content TEXT and
created_at DATETIME_IMMUTABLE, all NOT NULL, with column names left to the
naming strategy — exactly the declarations they replace, so swapping them for
the trait produces an empty doctrine:migrations:diff. CommentFieldsTest pins
this; a change there is a schema change in every consuming app.
#[ORM\HasLifecycleCallbacks] is not optional. The trait fills created_at
in a PrePersist callback, and Doctrine only runs callbacks on entities that
carry the attribute. Without it the insert fails on the NOT NULL column. The
callback only fills an empty timestamp, so fixtures and imports keep theirs.
The form
CommentType adds author, email, content and — unless
'spam_guard' => false — the configured guard as a spam_guard sub-form. It
has no submit button and no CSS classes. Labels and placeholders are these keys
in your messages domain:
comment.form.name comment.form.name_placeholder
comment.form.email comment.form.email_placeholder
comment.form.comment comment.form.comment_placeholder
comment.form.captcha_required
The controller only handles the form; a rejected submission is just an invalid one:
$form = $this->createForm(CommentType::class, $comment = new Comment());
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$comment->setBlogPost($post);
$this->publisher->publish($comment); // persist, flush, dispatch
$this->addFlash('success', 'Thanks!');
return $this->redirectToRoute(/* … */);
}
// Under Turbo, an invalid POST must answer 422 or the errors never render.
$status = $form->isSubmitted() ? 422 : 200;
And in the template, styled however your app styles forms:
{{ form_start(form) }}
{{ form_row(form.author) }}
{{ form_row(form.email) }}
{{ form_row(form.content) }}
{{ form_errors(form.spam_guard) }} {# stateless rejections land here #}
{{ form_row(form.spam_guard) }}
<button type="submit">Post comment</button>
{{ form_end(form) }}
The spam guards
Both implement SpamGuardInterface and are driven identically by
SpamGuardType. Both are always registered, so an app can use the one it did
not pick for comments directly — a contact form on the captcha, say.
math_captcha
"What is 3 + 7?", answer kept in the session. The answer input's label is set to
3 + 7 = ? on every render (change the format with the question_format
option of SpamGuardType). A wrong answer is an error on the answer field,
with the guard's reason as the error's cause.
Two properties that were learned the hard way:
- Answers are stored per token, up to
max_pendingat once. Turbo prefetches links on hover and people keep tabs open, so several rendered forms can be pending; a single session key makes every captcha but the newest one wrong. - Tokens are single-use, consumed whether or not the answer matches, so a bot cannot retry one question until it guesses right.
The question is minted when the form is rendered, not when it is built, so handling a POST leaves no unused answer behind, and the re-render after a failed POST asks a fresh question (the old token was just consumed).
Outside a comment form, call it directly:
['question' => $q, 'token' => $t] = $captcha->generate($session);
$ok = $captcha->validate($session, $request->request->get('captcha_token'), $answer);
stateless
No session, no database, no captcha — an anonymous visitor is never tracked, and
a bot learns nothing from a rejection: every reason shows the same message, and
the error lands on the spam_guard sub-form (render
form_errors(form.spam_guard)), with the specific reason in its cause for
your log. Four layers, cheapest first:
- Honeypot — a
websiteinput a human never sees. The guard renders it withtabindex="-1"andaria-hidden; hiding it visually is your CSS's job, since the package ships none — e.g.[name$="[spam_guard][website]"] { position: absolute; left: -9999px; }, or wrap the row in an off-screen element in your form theme. Prefer moving it off-screen overdisplay: none, which some bots detect and skip. - Time trap — the token is a timestamp signed with
secretwhen the form was rendered. Faster thanmin_secondswas not typed by a person; older thanmax_age_secondsis a replay. The signature includes acomment:context, so a stamp minted elsewhere with the same secret does not validate here. - Markup — anchors and BBCode are link-spam payloads.
- Link flood — more than
max_linksURLs across name and comment.
Proof of work (optional, since v1.1.0)
A CAPTCHA a reader never sees, with no session and no third party. Set
stateless.pow_difficulty to the number of leading zero bits the browser has
to find (16 is about 65,000 SHA-256 hashes: well under a second on a laptop, a
second or two on an old phone, and the form can be solving while the reader is
still typing). With it on:
- the token becomes
time:salt:signature, the salt signed along with the time, so every rendered form is its own puzzle; - the sub-form gets a hidden
proofinput carryingdata-pow-difficulty; - the submission passes only when
sha256(token + ":" + proof)starts with that many zero bits. A missing proof isproof_missing, a wrong oneproof_invalid— both shown with the same message as every other reason.
The package ships no JavaScript, so filling proof is the app's job. The
whole solver:
async function solve(token, bits) {
const enc = new TextEncoder();
for (let n = 0; ; n++) {
const h = new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode(token + ':' + n)));
let ok = true;
for (let i = 0, left = bits; left > 0; i++, left -= 8) {
const mask = left >= 8 ? 0xff : (0xff << (8 - left)) & 0xff;
if (h[i] & mask) { ok = false; break; }
}
if (ok) return String(n);
}
}
What it cannot do without state is make a solution single-use: one token and its proof verify until the stamp goes stale. It raises the price of every comment a bot posts from free to a few CPU-seconds; the cadence stays the rate limiter's job. A browser without JavaScript cannot comment while it is on.
The event
CommentPublisher::publish() persists, flushes, and only then dispatches
CommentPostedEvent, so a listener never announces a comment that failed to
save. It is deliberately not a Doctrine lifecycle hook: fixtures and imports
persist comments too, and nobody wants a notification per fixture row.
#[AsEventListener]
final class NotifyOnComment
{
public function __invoke(CommentPostedEvent $event): void
{
if (!$event->comment instanceof Comment) {
return;
}
// Build the message from your own entity and send it your way.
}
}
Twig helpers
Values only; the markup and colours stay yours.
| Function | Returns |
|---|---|
comment_initials(name) | first letter of the first and last word, upper-cased; ? for no name |
comment_avatar_index(name, count) | a stable index into your own list of count colours |
gravatar_url(email, size = 50, default = '404') | the Gravatar URL; d=404 lets you fall back to the initials |
They are multibyte throughout, because the Twig they replaced was (|first,
|upper and |length all use mbstring), and CommentsExtensionTest renders
the old inline Twig next to the functions to prove they agree.
Tests
composer install
vendor/bin/phpunit
vendor/bin/phpstan analyse # level 10
Run against both ends of the supported range before tagging:
composer update --prefer-lowest --prefer-stable && vendor/bin/phpunit
composer update && vendor/bin/phpunit