1: <?php
 2: 
 3: namespace Guzzle\Plugin\Md5;
 4: 
 5: use Guzzle\Common\Event;
 6: use Guzzle\Common\Exception\UnexpectedValueException;
 7: use Guzzle\Http\Message\Response;
 8: use Symfony\Component\EventDispatcher\EventSubscriberInterface;
 9: 
10: 11: 12: 13: 14: 
15: class Md5ValidatorPlugin implements EventSubscriberInterface
16: {
17:     18: 19: 
20:     protected $contentLengthCutoff;
21: 
22:     23: 24: 
25:     protected $contentEncoded;
26: 
27:     28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 
38:     public function __construct($contentEncoded = true, $contentLengthCutoff = false)
39:     {
40:         $this->contentLengthCutoff = $contentLengthCutoff;
41:         $this->contentEncoded = $contentEncoded;
42:     }
43: 
44:     45: 46: 
47:     public static function getSubscribedEvents()
48:     {
49:         return array('request.complete' => array('onRequestComplete', 255));
50:     }
51: 
52:     53: 54: 55: 
56:     public function onRequestComplete(Event $event)
57:     {
58:         $response = $event['response'];
59: 
60:         if (!$contentMd5 = $response->getContentMd5()) {
61:             return;
62:         }
63: 
64:         $contentEncoding = $response->getContentEncoding();
65:         if ($contentEncoding && !$this->contentEncoded) {
66:             return false;
67:         }
68: 
69:         
70:         if ($this->contentLengthCutoff) {
71:             $size = $response->getContentLength() ?: $response->getBody()->getSize();
72:             if (!$size || $size > $this->contentLengthCutoff) {
73:                 return;
74:             }
75:         }
76: 
77:         if (!$contentEncoding) {
78:             $hash = $response->getBody()->getContentMd5();
79:         } elseif ($contentEncoding == 'gzip') {
80:             $response->getBody()->compress('zlib.deflate');
81:             $hash = $response->getBody()->getContentMd5();
82:             $response->getBody()->uncompress();
83:         } elseif ($contentEncoding == 'compress') {
84:             $response->getBody()->compress('bzip2.compress');
85:             $hash = $response->getBody()->getContentMd5();
86:             $response->getBody()->uncompress();
87:         } else {
88:             return;
89:         }
90: 
91:         if ($contentMd5 !== $hash) {
92:             throw new UnexpectedValueException(
93:                 "The response entity body may have been modified over the wire.  The Content-MD5 "
94:                 . "received ({$contentMd5}) did not match the calculated MD5 hash ({$hash})."
95:             );
96:         }
97:     }
98: }
99: