The ninth and last episode of the Shopware plugin series. Video here, code in the GitHub repo.
Questions nobody answers
Not every customer question gets an answer. Some are spam, some were answered somewhere else. Over a few months they pile up in the admin list. Instead of asking the shop owner to clean up by hand, Shopware can do it once a day with a scheduled task.
Task and handler
A scheduled task has two parts. The task says what and how often. The handler does the work.
Shopware's scheduler checks which tasks are due and puts a message on the queue for each one. A worker picks the message up and runs the handler. So the work happens in the background, not during somebody's page load.
The task
The task class is tiny. It has a name, an interval, and an answer to "what if it fails":
class DeleteUnansweredQuestionsTask extends ScheduledTask
{
public static function getTaskName(): string
{
return 'runio_product_faq.delete_unanswered';
}
public static function getDefaultInterval(): int
{
return self::DAILY;
}
// If a run fails, try again at the next interval instead of stopping the task
public static function shouldRescheduleOnFailure(): bool
{
return true;
}
}
The handler
The handler extends ScheduledTaskHandler, and the AsMessageHandler attribute connects it to our task:
#[AsMessageHandler(handles: DeleteUnansweredQuestionsTask::class)]
final class DeleteUnansweredQuestionsTaskHandler extends ScheduledTaskHandler
First it reads the number of days from the plugin settings. Zero means "keep them forever", so the handler stops right there:
$days = $this->systemConfigService->getInt('RunioProductFaq.config.deleteUnansweredAfterDays');
// 0 keeps unanswered questions forever
if ($days <= 0) {
return;
}
// createdAt is stored in UTC
$before = $this->now()->setTimezone(new \DateTimeZone('UTC'))->modify(\sprintf('-%d days', $days));
The date comes from Shopware's clock through $this->now(), not from new DateTime(). Two reasons: it has to be UTC like createdAt in the database, and in tests the clock can be set to any day. That makes "is a 91-day-old question deleted?" easy to test without waiting three months.
Then it looks for what should go: inactive, no answer, older than the cutoff. A draft that already has an answer stays, because the shop owner is probably still working on it.
$criteria = (new Criteria())
->addFilter(new EqualsFilter('active', false))
->addFilter(new OrFilter([
new EqualsFilter('answer', null),
new EqualsFilter('answer', ''),
]))
->addFilter(new RangeFilter('createdAt', [
RangeFilter::LT => $before->format(Defaults::STORAGE_DATE_TIME_FORMAT),
]))
->setLimit(self::BATCH_SIZE);
Deleting in batches
The handler deletes 500 at a time, so a big backlog never has to be loaded at once:
$previous = [];
while ($ids = $this->faqRepository->searchIds($criteria, $context)->getIds()) {
if (array_intersect($ids, $previous)) {
break;
}
$this->faqRepository->delete(array_map(static fn (string $id): array => ['id' => $id], $ids), $context);
$previous = $ids;
}
The array_intersect check is a safety net. If a batch ever comes back with IDs we already deleted, something stopped the delete, and the loop ends instead of running forever. A background job that spins in a loop is a hard thing to notice, so I'd rather have it stop.
Wiring and settings
In services.php the task gets the shopware.scheduled.task tag and the handler gets messenger.message_handler:
$services->set(DeleteUnansweredQuestionsTask::class)
->tag('shopware.scheduled.task');
$services->set(DeleteUnansweredQuestionsTaskHandler::class)
->args([/* ... */])
->tag('messenger.message_handler');
And config.xml adds the setting to the plugin's configuration page, the same way as the announcement bar text in episode one:
<input-field type="int">
<name>deleteUnansweredAfterDays</name>
<label>Delete unanswered questions after (days)</label>
<helpText>A daily task deletes inactive questions without an answer that are older than this. 0 keeps them forever.</helpText>
<defaultValue>90</defaultValue>
<min>0</min>
</input-field>
Trying it
After updating the plugin, bin/console scheduled-task:list shows the task, running once a day. To test it now instead of tomorrow:
bin/console scheduled-task:run-single runio_product_faq.delete_unanswered
The four-month-old question is gone. Last week's question stays, and so does the draft with an answer. In the admin the shop owner can change the number of days, or switch the clean-up off with zero.
Recap, and the end of the series
A task with a name and an interval, a handler that works in batches, two service tags and a setting in config.xml.
That finishes the Product FAQ plugin. Over nine episodes it went from an empty skeleton to a custom entity with an admin module, live search, a Store API route, a CMS element, customer questions, a Flow Builder trigger and a daily clean-up. The code for every step is in the GitHub repo, one folder per episode. Thanks for reading along.
Author Amer Malik Mohammed
Full-Stack Developer with 2+ years of experience in object-oriented PHP development (Symfony), JavaScript and MySQL. Specialized in e-commerce solutions (Shopware 5/6), REST API development and process automation in agile teams.
Contact author