<?php
namespace Products\NotificationsBundle\Form\Forms\Messages;
use Products\NotificationsBundle\Entity\Notifications\Message;
use Products\NotificationsBundle\Entity\Recording;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class ScriptChangeDetectionListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
FormEvents::PRE_SUBMIT => 'onPreSubmit',
];
}
public function onPreSubmit(FormEvent $event)
{
$message = $event->getForm()->getData();
if ( ! ($message instanceof Message)) {
return;
}
$originalRecording = $message->getRecording();
if (! ($originalRecording instanceof Recording)) {
return;
}
$formData = $event->getData();
$originalScript = $message->getScript();
$currentScript = $formData['script'] ?? '';
$strippedOriginalScript = trim(preg_replace('/\s+/', ' ', $originalScript));
$strippedCurrentScript = trim(preg_replace('/\s+/', ' ', $currentScript));
$isScriptModified = ($strippedOriginalScript !== $strippedCurrentScript);
$currentRecordingJson = $formData['recording'] ?? '';
$currentRecordingData = json_decode($currentRecordingJson, true);
$isRecordingModified = (
(json_last_error() === JSON_ERROR_NONE) &&
isset($currentRecordingData['id']) &&
($originalRecording->getId() !== $currentRecordingData['id'])
);
if ($isScriptModified && ! $isRecordingModified) {
$event->getForm()->addError(new FormError('Voice transcript has changed. Click "Convert text to speech".'));
}
}
}