4
0
api-powers/src/c99e85a0-d120-4f25-bcbf-0940dd7b773b/code.power

97 lines
2.5 KiB
Plaintext
Raw Permalink Normal View History

2023-09-26 06:24:03 +00:00
/**
* Process the response and decode it.
*
* @param JoomlaResponse $response The response.
* @param integer $expectedCode The expected "good" code.
* @param mixed $default The default if body not have length
*
* @return mixed
*
* @since 2.0.1
* @throws \DomainException
**/
2024-01-25 11:19:06 +00:00
public function get($response, int $expectedCode = 200, $default = null)
2023-09-26 06:24:03 +00:00
{
// Validate the response code.
if ($response->code != $expectedCode)
{
// Decode the error response and throw an exception.
$message = $this->error($response);
// Throw an exception with the GetBible error message and code.
throw new \DomainException($message, $response->code);
}
return $this->getBody($response, $default);
}
/**
* Return the body from the response
*
* @param JoomlaResponse $response The response.
* @param mixed $default The default if body not have length
*
* @return mixed
* @since 2.0.1
**/
2024-01-25 11:19:06 +00:00
protected function getBody($response, $default = null)
2023-09-26 06:24:03 +00:00
{
2024-01-23 05:44:03 +00:00
$body = $response->body ?? null;
2023-09-26 06:24:03 +00:00
// check that we have a body
2024-01-23 05:44:03 +00:00
if (StringHelper::check($body))
2023-09-26 06:24:03 +00:00
{
// if it's JSON, decode it
2024-01-23 05:44:03 +00:00
if (JsonHelper::check($body))
2023-09-26 06:24:03 +00:00
{
2024-01-23 05:44:03 +00:00
return json_decode((string) $body);
2023-09-26 06:24:03 +00:00
}
// if it's XML, convert it to an object
libxml_use_internal_errors(true);
2024-01-23 05:44:03 +00:00
$xml = simplexml_load_string($body);
2023-09-26 06:24:03 +00:00
if ($xml !== false)
{
return $xml;
}
// if it's neither JSON nor XML, return as is
2024-01-23 05:44:03 +00:00
return $body;
2023-09-26 06:24:03 +00:00
}
return $default;
}
/**
* Get the error message from the GetBible API response
*
* @param JoomlaResponse $response The response.
*
* @return string
* @since 2.0.1
**/
2024-01-25 11:19:06 +00:00
protected function error($response): string
2023-09-26 06:24:03 +00:00
{
2024-01-23 05:44:03 +00:00
$body = $response->body ?? null;
2023-09-26 06:24:03 +00:00
// do we have a json string
2024-01-23 05:44:03 +00:00
if (JsonHelper::check($body))
2023-09-26 06:24:03 +00:00
{
2024-01-23 05:44:03 +00:00
$error = json_decode($body);
2023-09-26 06:24:03 +00:00
}
else
{
return 'Invalid or empty response body.';
}
// check if GetBible returned an error object
if (isset($error->Error))
{
// error object found, extract message and code
$errorMessage = isset($error->Error->Message) ? $error->Error->Message : 'Unknown error.';
$errorCode = isset($error->Error->Code) ? $error->Error->Code : 'Unknown error code.';
// return formatted error message
return 'Wasabi Error: ' . $errorMessage . ' Code: ' . $errorCode;
}
return 'No error information found in response.';
}