1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73:
<?php
namespace Guzzle\Plugin\ErrorResponse;
use Guzzle\Common\Event;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Description\Operation;
use Guzzle\Plugin\ErrorResponse\Exception\ErrorResponseException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ErrorResponsePlugin implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array('command.before_send' => array('onCommandBeforeSend', -1));
}
public function onCommandBeforeSend(Event $event)
{
$command = $event['command'];
if ($operation = $command->getOperation()) {
if ($operation->getErrorResponses()) {
$request = $command->getRequest();
$request->getEventDispatcher()
->addListener('request.complete', $this->getErrorClosure($request, $command, $operation));
}
}
}
protected function getErrorClosure(RequestInterface $request, CommandInterface $command, Operation $operation)
{
return function (Event $event) use ($request, $command, $operation) {
$response = $event['response'];
foreach ($operation->getErrorResponses() as $error) {
if (!isset($error['class'])) {
continue;
}
if (isset($error['code']) && $response->getStatusCode() != $error['code']) {
continue;
}
if (isset($error['reason']) && $response->getReasonPhrase() != $error['reason']) {
continue;
}
$className = $error['class'];
$errorClassInterface = __NAMESPACE__ . '\\ErrorResponseExceptionInterface';
if (!class_exists($className)) {
throw new ErrorResponseException("{$className} does not exist");
} elseif (!(in_array($errorClassInterface, class_implements($className)))) {
throw new ErrorResponseException("{$className} must implement {$errorClassInterface}");
}
throw $className::fromCommand($command, $response);
}
};
}
}