1. <?php
  2. use Google\Cloud\Tasks\V2\TaskClient;
  3. use Google\Cloud\Tasks\V2\Task;
  4. use Google\Cloud\Tasks\V2\TaskQueue;
  5. use Google\Cloud\Tasks\V2\Projects\TasksClient;
  6. /**
  7. * Serializes task queue objects for diagnostics with rate limiting.
  8. *
  9. * @param TaskQueue $taskQueue The task queue object to serialize.
  10. * @param array $rateLimitInfo Array containing rate limit information.
  11. *
  12. * @return string Serialized JSON string.
  13. * @throws \Exception If serialization fails.
  14. */
  15. function serializeTaskQueueWithRateLimit(TaskQueue $taskQueue, array $rateLimitInfo): string
  16. {
  17. // Prepare data for serialization
  18. $data = [
  19. 'name' => $taskQueue->getName(),
  20. 'location' => $taskQueue->getLocation(),
  21. 'description' => $taskQueue->getDescription(),
  22. 'projectId' => $taskQueue->getProjectId(),
  23. 'rateLimit' => $rateLimitInfo,
  24. ];
  25. // Serialize to JSON
  26. $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  27. if ($json === false) {
  28. throw new \Exception('JSON encoding failed.');
  29. }
  30. return $json;
  31. }
  32. /**
  33. * Example usage (requires Google Cloud Tasks API setup)
  34. */
  35. /*
  36. try {
  37. // Initialize Tasks client
  38. $client = new TasksClient();
  39. // Get the task queue
  40. $taskQueue = $client->taskQueues->get('your-project-id', 'your-location', 'your-task-queue-name');
  41. //Sample rate limit information. Replace with your actual rate limit.
  42. $rateLimitInfo = [
  43. 'limit' => 100, // Maximum number of tasks per minute
  44. 'window' => 60, // Time window in seconds
  45. 'resetTime' => time() // Timestamp of the window start
  46. ];
  47. // Serialize the task queue data with rate limit information
  48. $serializedData = serializeTaskQueueWithRateLimit($taskQueue, $rateLimitInfo);
  49. // Output the serialized data (for diagnostics)
  50. echo $serializedData . PHP_EOL;
  51. } catch (\Exception $e) {
  52. echo "Error: " . $e->getMessage() . PHP_EOL;
  53. }
  54. */
  55. ?>

Add your comment