1: <?php
2:
3: namespace Guzzle\Plugin\Cookie;
4:
5: use Guzzle\Common\Event;
6: use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;
7: use Guzzle\Plugin\Cookie\CookieJar\CookieJarInterface;
8: use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9:
10: /**
11: * Adds, extracts, and persists cookies between HTTP requests
12: */
13: class CookiePlugin implements EventSubscriberInterface
14: {
15: /**
16: * @var CookieJarInterface Cookie cookieJar used to hold cookies
17: */
18: protected $cookieJar;
19:
20: /**
21: * @param CookieJarInterface $cookieJar Cookie jar used to hold cookies. Creates an ArrayCookieJar by default.
22: */
23: public function __construct(CookieJarInterface $cookieJar = null)
24: {
25: $this->cookieJar = $cookieJar ?: new ArrayCookieJar();
26: }
27:
28: /**
29: * {@inheritdoc}
30: */
31: public static function getSubscribedEvents()
32: {
33: return array(
34: 'request.before_send' => array('onRequestBeforeSend', 125),
35: 'request.sent' => array('onRequestSent', 125)
36: );
37: }
38:
39: /**
40: * Get the cookie cookieJar
41: *
42: * @return CookieJarInterface
43: */
44: public function getCookieJar()
45: {
46: return $this->cookieJar;
47: }
48:
49: /**
50: * Add cookies before a request is sent
51: *
52: * @param Event $event
53: */
54: public function onRequestBeforeSend(Event $event)
55: {
56: $request = $event['request'];
57: if (!$request->getParams()->get('cookies.disable')) {
58: $request->removeHeader('Cookie');
59: // Find cookies that match this request
60: foreach ($this->cookieJar->getMatchingCookies($request) as $cookie) {
61: $request->addCookie($cookie->getName(), $cookie->getValue());
62: }
63: }
64: }
65:
66: /**
67: * Extract cookies from a sent request
68: *
69: * @param Event $event
70: */
71: public function onRequestSent(Event $event)
72: {
73: $this->cookieJar->addCookiesFromResponse($event['response']);
74: }
75: }
76: