1. <?php
  2. /**
  3. * Removes duplicate HTTP responses.
  4. *
  5. * This function takes an array of HTTP response objects and returns a new array
  6. * with duplicates removed. It's designed for development use and doesn't
  7. * rely on external libraries. It compares responses based on their content.
  8. *
  9. * @param array $responses An array of HTTP response objects. Each object
  10. * should have a 'body' property containing the response content.
  11. * @return array A new array with duplicate HTTP responses removed.
  12. */
  13. function removeDuplicateResponses(array $responses): array
  14. {
  15. $uniqueResponses = [];
  16. $seenBodies = []; // Keep track of response bodies we've already encountered.
  17. foreach ($responses as $response) {
  18. // Check if the response body has been seen before.
  19. if (!in_array($response['body'], $seenBodies)) {
  20. $uniqueResponses[] = $response; // Add the response to the unique array.
  21. $seenBodies[] = $response['body']; // Add the response body to the seen array.
  22. }
  23. }
  24. return $uniqueResponses;
  25. }
  26. // Example Usage (for testing)
  27. /*
  28. class HttpResponse {
  29. public $status_code;
  30. public $body;
  31. public function __construct($status_code, $body) {
  32. $this->status_code = $status_code;
  33. $this->body = $body;
  34. }
  35. }
  36. $response1 = new HttpResponse(200, 'This is the first response.');
  37. $response2 = new HttpResponse(200, 'This is the first response.');
  38. $response3 = new HttpResponse(302, 'This is a different response.');
  39. $response4 = new HttpResponse(200, 'This is the first response.'); // Duplicate
  40. $responses = [$response1, $response2, $response3, $response4];
  41. $uniqueResponses = removeDuplicateResponses($responses);
  42. foreach ($uniqueResponses as $response) {
  43. echo "Status Code: " . $response->status_code . "\n";
  44. echo "Body: " . $response->body . "\n";
  45. echo "\n";
  46. }
  47. */
  48. ?>

Add your comment