1: <?php
2:
3: namespace Guzzle\Plugin\Md5;
4:
5: use Guzzle\Common\Event;
6: use Guzzle\Http\Message\EntityEnclosingRequestInterface;
7: use Symfony\Component\EventDispatcher\EventSubscriberInterface;
8:
9: /**
10: * Listener used to add a ContentMD5 header to the body of a command and adds ContentMD5 validation if the
11: * ValidateMD5 option is not set to false on a command
12: */
13: class CommandContentMd5Plugin implements EventSubscriberInterface
14: {
15: /**
16: * @var string Parameter used to check if the ContentMD5 value is being added
17: */
18: protected $contentMd5Param;
19:
20: /**
21: * @var string Parameter used to check if validation should occur on the response
22: */
23: protected $validateMd5Param;
24:
25: /**
26: * @param string $contentMd5Param Parameter used to check if the ContentMD5 value is being added
27: * @param string $validateMd5Param Parameter used to check if validation should occur on the response
28: */
29: public function __construct($contentMd5Param = 'ContentMD5', $validateMd5Param = 'ValidateMD5')
30: {
31: $this->contentMd5Param = $contentMd5Param;
32: $this->validateMd5Param = $validateMd5Param;
33: }
34:
35: /**
36: * {@inheritdoc}
37: */
38: public static function getSubscribedEvents()
39: {
40: return array('command.before_send' => array('onCommandBeforeSend', -255));
41: }
42:
43: /**
44: * {@inheritdoc}
45: */
46: public function onCommandBeforeSend(Event $event)
47: {
48: $command = $event['command'];
49: $request = $command->getRequest();
50:
51: // Only add an MD5 is there is a MD5 option on the operation and it has a payload
52: if ($request instanceof EntityEnclosingRequestInterface && $request->getBody()
53: && $command->getOperation()->hasParam($this->contentMd5Param)) {
54: // Check if an MD5 checksum value should be passed along to the request
55: if ($command[$this->contentMd5Param] === true) {
56: $request->setHeader('Content-MD5', $request->getBody()->getContentMd5(true, true));
57: }
58: }
59:
60: // Check if MD5 validation should be used with the response
61: if ($command[$this->validateMd5Param] === true) {
62: $request->addSubscriber(new Md5ValidatorPlugin(true, false));
63: }
64: }
65: }
66: