/wp-content/plugins/google-listings-and-ads/vendor/googleads/google-ads-php/src/Google/Ads/GoogleAds/Lib/V9/LogMessageFormatter.php

https://gitlab.com/remyvianne/krowkaramel · PHP · 173 lines · 105 code · 20 blank · 48 comment · 5 complexity · 72ad567ed8ae8e5675898512a9980c8c MD5 · raw file

  1. <?php
  2. /**
  3. * Copyright 2020 Google LLC
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * https://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. namespace Google\Ads\GoogleAds\Lib\V9;
  18. use Google\ApiCore\ArrayTrait;
  19. use Google\Protobuf\Internal\Message;
  20. /**
  21. * Formats information about a single gRPC / REST call for logging.
  22. */
  23. final class LogMessageFormatter
  24. {
  25. use ArrayTrait;
  26. use GoogleAdsMetadataTrait;
  27. private $statusMetadataExtractor;
  28. private $infoRedactor;
  29. public function __construct(
  30. StatusMetadataExtractor $statusMetadataExtractor = null,
  31. InfoRedactor $infoRedactor = null
  32. ) {
  33. $this->statusMetadataExtractor = $statusMetadataExtractor ?? new StatusMetadataExtractor();
  34. $this->infoRedactor = $infoRedactor ?? new InfoRedactor();
  35. }
  36. /**
  37. * Extracts the customer ID, if present, from the provided request.
  38. *
  39. * @param Message $request the request to get its customer ID
  40. * @return string the customer ID if present or the message saying that the customer ID is not
  41. * available
  42. */
  43. private static function extractCustomerId(Message $request): string
  44. {
  45. // Most requests contain customer ID in the request, so we aim to extract that.
  46. if (method_exists($request, 'getCustomerId')) {
  47. return $request->getCustomerId();
  48. } elseif (method_exists($request, 'getResourceName')) {
  49. // In some cases, customer ID is available in the form of resource name, such as many
  50. // Get requests.
  51. $resourceName = $request->getResourceName();
  52. $segments = explode('/', $resourceName);
  53. if ($segments[0] === 'customers') {
  54. return $segments[1];
  55. }
  56. }
  57. return '"No customer ID could be extracted from the request"';
  58. }
  59. /**
  60. * Formats the request and response data for summary logging.
  61. *
  62. * @param array $requestData the request data
  63. * @param array $responseData the response data
  64. * @param string $endpoint the API endpoint that the request has been sent to
  65. * @return string the formatted logging message
  66. */
  67. public function formatSummary(
  68. array $requestData,
  69. array $responseData,
  70. $endpoint
  71. ) {
  72. $method = $this->pluck('method', $requestData);
  73. $argument = $this->pluck('argument', $requestData);
  74. $status = $this->pluck('status', $responseData);
  75. if ($status->code !== 0) {
  76. $errorMessageList =
  77. $this->statusMetadataExtractor->extractErrorMessageList($status->metadata);
  78. }
  79. return sprintf(
  80. 'Request made: Host: "%s", Method: "%s", CustomerId: %s, RequestId: "%s", '
  81. . 'IsFault: %b, FaultMessage: "%s"',
  82. $endpoint,
  83. $method,
  84. self::extractCustomerId($argument),
  85. $this->getFirstHeaderValue(self::$REQUEST_ID_HEADER_KEY, $status->metadata),
  86. $status->code !== 0,
  87. !empty($errorMessageList) ? json_encode($errorMessageList) : 'None'
  88. );
  89. }
  90. /**
  91. * Formats the request and response data for detailed logging.
  92. *
  93. * @param array $requestData the request data
  94. * @param array $responseData the response data
  95. * @param string $endpoint the API endpoint that the request has been sent to
  96. * @return string the formatted logging message
  97. */
  98. public function formatDetail(
  99. array $requestData,
  100. array $responseData,
  101. $endpoint
  102. ) {
  103. $logMessageTokens = [];
  104. $method = $this->pluck('method', $requestData);
  105. $argument = $this->pluck('argument', $requestData);
  106. $metadata = $this->pluck('metadata', $requestData) ?: [];
  107. $response = $this->pluck('response', $responseData);
  108. $status = $this->pluck('status', $responseData);
  109. $call = $this->pluck('call', $responseData);
  110. $logMessageTokens[] = 'Request';
  111. $logMessageTokens[] = '-------';
  112. $logMessageTokens[] = "Method Name: $method";
  113. $logMessageTokens[] = "Host: $endpoint";
  114. $logMessageTokens[] = "Headers: " . json_encode(
  115. $this->infoRedactor->redactHeaders(self::joinPluckedArrays($metadata)),
  116. JSON_PRETTY_PRINT
  117. );
  118. $logMessageTokens[] = "Request: ";
  119. $logMessageTokens[] = $this->infoRedactor->redactBody($argument)->serializeToJsonString();
  120. $logMessageTokens[] = "\nResponse";
  121. $logMessageTokens[] = '-------';
  122. $logMessageTokens[] = "Headers: " . json_encode(
  123. self::joinPluckedArrays($call->getMetadata()),
  124. JSON_PRETTY_PRINT
  125. );
  126. if ($status->code === 0) {
  127. $logMessageTokens[] = "Response: ";
  128. $logMessageTokens[] = is_null($response)
  129. ? "None" : $this->infoRedactor->redactBody($response)->serializeToJsonString();
  130. } else {
  131. $googleAdsFailure =
  132. $this->statusMetadataExtractor->extractGoogleAdsFailure($status->metadata);
  133. $logMessageTokens[] = "\nFault";
  134. $logMessageTokens[] = '-------';
  135. $logMessageTokens[] = "Status code: {$status->code}";
  136. $logMessageTokens[] = "Details: {$status->details}";
  137. $logMessageTokens[] = "Failure: {$googleAdsFailure->serializeToJsonString()}";
  138. }
  139. return implode("\n", $logMessageTokens);
  140. }
  141. /**
  142. * @param array $array
  143. * @return array the joined array after plucking
  144. */
  145. private function joinPluckedArrays(array $array)
  146. {
  147. $joinedArray = [];
  148. foreach (array_keys($array) as $key) {
  149. $joinedArray[$key] = $this->pluck($key, $array)[0];
  150. }
  151. return $joinedArray;
  152. }
  153. }