wse-1.0.x-dev/modules/wse_task_monitor/tests/modules/wse_task_monitor_test/src/EventSubscriber/BackupTaskEventSubscriber.php
modules/wse_task_monitor/tests/modules/wse_task_monitor_test/src/EventSubscriber/BackupTaskEventSubscriber.php
<?php
declare(strict_types=1);
namespace Drupal\wse_task_monitor_test\EventSubscriber;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\wse_task_monitor_test\WorkspaceBackupTaskMonitor;
use Drupal\wse_task_monitor\WorkspaceTaskRepositoryInterface;
use Drupal\workspaces\Event\WorkspacePrePublishEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Event subscriber that creates backup tasks before workspace publishing.
*/
class BackupTaskEventSubscriber implements EventSubscriberInterface {
public function __construct(
protected readonly WorkspaceTaskRepositoryInterface $repository,
protected readonly WorkspaceBackupTaskMonitor $backupTaskMonitor,
protected readonly FileSystemInterface $fileSystem,
protected readonly TimeInterface $time,
) {}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
return [
WorkspacePrePublishEvent::class => ['onPrePublish', 100],
];
}
/**
* Reacts to workspace pre-publish event to create backup task.
*/
public function onPrePublish(WorkspacePrePublishEvent $event): void {
$workspace = $event->getWorkspace();
// Create backup task.
$task = $this->backupTaskMonitor->createTask($workspace);
$task_id = $task->getId();
// Write initial progress file.
$this->writeProgressToFile($task_id, 0, 'Starting backup...');
// Simulate 10-second backup with progress updates to file.
for ($i = 0; $i <= 10; $i++) {
$progress = (int) (($i / 10) * 100);
$message = $this->getProgressMessage($i);
// Write progress to file.
$this->writeProgressToFile($task_id, $progress, $message);
sleep(1);
}
}
/**
* Writes progress data to temp file.
*/
private function writeProgressToFile(string $task_id, int $progress, string $message): void {
$temp_dir = $this->fileSystem->getTempDirectory();
$progress_file_path = $temp_dir . '/wse_backup_' . $task_id . '.json';
$progress_data = [
'task_id' => $task_id,
'progress' => $progress,
'message' => $message,
'timestamp' => $this->time->getRequestTime(),
];
file_put_contents($progress_file_path, json_encode($progress_data));
}
/**
* Gets progress message based on iteration.
*/
private function getProgressMessage(int $iteration): string {
if ($iteration < 3) {
return 'Initializing backup process...';
}
if ($iteration < 5) {
return 'Preparing backup directory...';
}
if ($iteration < 7) {
return 'Backing up database schema...';
}
if ($iteration < 10) {
return 'Backing up database data...';
}
return 'Finalizing backup...';
}
}
