1<?php
2namespace GuzzleHttp\Subscriber;
3
4use GuzzleHttp\Cookie\CookieJar;
5use GuzzleHttp\Cookie\CookieJarInterface;
6use GuzzleHttp\Event\BeforeEvent;
7use GuzzleHttp\Event\CompleteEvent;
8use GuzzleHttp\Event\RequestEvents;
9use GuzzleHttp\Event\SubscriberInterface;
10
11/**
12 * Adds, extracts, and persists cookies between HTTP requests
13 */
14class Cookie implements SubscriberInterface
15{
16    /** @var CookieJarInterface */
17    private $cookieJar;
18
19    /**
20     * @param CookieJarInterface $cookieJar Cookie jar used to hold cookies
21     */
22    public function __construct(CookieJarInterface $cookieJar = null)
23    {
24        $this->cookieJar = $cookieJar ?: new CookieJar();
25    }
26
27    public function getEvents()
28    {
29        // Fire the cookie plugin complete event before redirecting
30        return [
31            'before'   => ['onBefore'],
32            'complete' => ['onComplete', RequestEvents::REDIRECT_RESPONSE + 10]
33        ];
34    }
35
36    /**
37     * Get the cookie cookieJar
38     *
39     * @return CookieJarInterface
40     */
41    public function getCookieJar()
42    {
43        return $this->cookieJar;
44    }
45
46    public function onBefore(BeforeEvent $event)
47    {
48        $this->cookieJar->addCookieHeader($event->getRequest());
49    }
50
51    public function onComplete(CompleteEvent $event)
52    {
53        $this->cookieJar->extractCookies(
54            $event->getRequest(),
55            $event->getResponse()
56        );
57    }
58}
59