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