Check Status Code of responses (especially for POST/PUT/DELETE requests)
Art4 opened this issue · comments
After requesting the Redmine server in Redmine\Api\...
classes we should check for the correct status code in the responses, see #341. Otherwise we should throw an UnexpectedResponseException
, see #364.
Throwing an exception would be a breaking change, so this change has to be made in a forward compatible way, or in the next major version.
A FC way could look like this:
// in \Redmine\Api\Project
public function update($id, array $params)
{
// ...
$result = $this->put(
'/projects/' . $id . '.xml',
XmlSerializer::createFromArray(['project' => $params])->getEncoded()
);
$lastResponse = $this->getLastResponse();
if ($lastResponse->getStatusCode() !== 204) {
if (!defined('PHP_REDMINE_API_THROW_EXCEPTIONS_ON_STATUS_CODE_MISSMATCH') || PHP_REDMINE_API_THROW_EXCEPTIONS_ON_STATUS_CODE_MISSMATCH !== true) {
trigger_error(
sprintf(
'The Redmine server replied with the status code %d in %s(), starting with v2.0.0 this will throw an %s. Define the constant `%s` to throw the exceptions now.',
$lastResponse->getStatusCode(),
__METHOD__,
UnexpectedResponseException::class,
'PHP_REDMINE_API_THROW_EXCEPTIONS_ON_STATUS_CODE_MISSMATCH'
),
E_USER_DEPRECATED
);
return $result;
}
throw new UnexpectedResponseException($lastResponse);
}
return true;
}
In v3 we could just remove the check.
// in \Redmine\Api\Project
public function update($id, array $params)
{
// ...
$result = $this->put(
'/projects/' . $id . '.xml',
XmlSerializer::createFromArray(['project' => $params])->getEncoded()
);
$lastResponse = $this->getLastResponse();
if ($lastResponse->getStatusCode() !== 204) {
throw new UnexpectedResponseException($lastResponse);
}
return true;
}