wse-1.0.x-dev/modules/wse_task_monitor/tests/modules/wse_task_monitor_test/src/WorkspaceBackupTaskMonitor.php

modules/wse_task_monitor/tests/modules/wse_task_monitor_test/src/WorkspaceBackupTaskMonitor.php
<?php

declare(strict_types=1);

namespace Drupal\wse_task_monitor_test;

use Drupal\Core\Logger\LoggerChannelInterface;
use Drupal\Core\Url;
use Drupal\wse_task_monitor\WorkspaceTaskMonitorInterface;
use Drupal\wse_task_monitor\WorkspaceTaskRepositoryInterface;
use Drupal\wse_task_monitor\WorkspaceTask;
use Drupal\workspaces\WorkspaceInterface;
use GuzzleHttp\ClientInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

/**
 * Task monitor for workspace backup operations.
 */
class WorkspaceBackupTaskMonitor implements WorkspaceTaskMonitorInterface {

  public function __construct(
    protected readonly ClientInterface $httpClient,
    #[Autowire(service: 'logger.channel.workspaces')]
    protected readonly LoggerChannelInterface $logger,
    protected readonly WorkspaceTaskRepositoryInterface $repository,
  ) {}

  /**
   * {@inheritdoc}
   */
  public function createTask(WorkspaceInterface $workspace, array $context = []): WorkspaceTask {
    $task_id = $this->repository->generateTaskId();

    // Use provided progress URL or generate mock URL.
    $progress_url = $context['progress_url'] ?? Url::fromRoute('wse_task_monitor_test.mock_backup_status', [
      'task_id' => $task_id,
    ], ['absolute' => TRUE])->toString();

    $task = new WorkspaceTask(
      $task_id,
      $workspace->id(),
      self::class,
      $context['label'] ?? 'Creating database backup.',
      [
        'progress_url' => $progress_url,
      ]
    );

    $task->start('Starting backup...');
    $this->repository->save($task);

    return $task;
  }

  /**
   * {@inheritdoc}
   */
  public function getTaskProgress(WorkspaceTask $task): ?array {
    // Get progress URL from task metadata.
    $url = $task->getMetadataValue('progress_url');
    if (!$url) {
      return NULL;
    }

    try {
      $response = $this->httpClient->get($url);
      $data = json_decode($response->getBody()->getContents(), TRUE);

      if ($data && isset($data['status']) && isset($data['progress'])) {
        // Use the message from the API response (which comes from the task).
        return [
          'progress' => (int) ($data['progress'] ?? 0),
          'message' => $data['description'] ?? 'Processing...',
          'status' => $data['status'] ?? 'unknown',
        ];
      }
    }
    catch (\Exception $e) {
      $this->logger->error('Failed to fetch backup progress for task @id: @error', [
        '@id' => $task->getId(),
        '@error' => $e->getMessage(),
      ]);
    }

    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function cleanup(WorkspaceTask $task): void {
    // No cleanup needed for backup tasks.
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc