10 * Cookie holder object
15 class Requests_Cookie_Jar implements ArrayAccess, IteratorAggregate {
21 protected $cookies = array();
26 * @param array $cookies Existing cookie values
28 public function __construct($cookies = array()) {
29 $this->cookies = $cookies;
33 * Normalise cookie data into a Requests_Cookie
35 * @param string|Requests_Cookie $cookie
36 * @return Requests_Cookie
38 public function normalizeCookie($cookie, $key = null) {
39 if ($cookie instanceof Requests_Cookie) {
43 return Requests_Cookie::parse($cookie, $key);
47 * Check if the given item exists
49 * @param string $key Item key
50 * @return boolean Does the item exist?
52 public function offsetExists($key) {
53 return isset($this->cookies[$key]);
57 * Get the value for the item
59 * @param string $key Item key
60 * @return string Item value
62 public function offsetGet($key) {
63 if (!isset($this->cookies[$key]))
66 return $this->cookies[$key];
72 * @throws Requests_Exception On attempting to use dictionary as list (`invalidset`)
74 * @param string $key Item name
75 * @param string $value Item value
77 public function offsetSet($key, $value) {
79 throw new Requests_Exception('Object is a dictionary, not a list', 'invalidset');
82 $this->cookies[$key] = $value;
86 * Unset the given header
90 public function offsetUnset($key) {
91 unset($this->cookies[$key]);
95 * Get an iterator for the data
97 * @return ArrayIterator
99 public function getIterator() {
100 return new ArrayIterator($this->cookies);
104 * Register the cookie handler with the request's hooking system
106 * @param Requests_Hooker $hooks Hooking system
108 public function register(Requests_Hooker $hooks) {
109 $hooks->register('requests.before_request', array($this, 'before_request'));
110 $hooks->register('requests.before_redirect_check', array($this, 'before_redirect_check'));
114 * Add Cookie header to a request if we have any
116 * As per RFC 6265, cookies are separated by '; '
119 * @param array $headers
121 * @param string $type
122 * @param array $options
124 public function before_request(&$url, &$headers, &$data, &$type, &$options) {
125 if (!empty($this->cookies)) {
127 foreach ($this->cookies as $key => $cookie) {
128 $cookie = $this->normalizeCookie($cookie, $key);
129 $cookies[] = $cookie->formatForHeader();
132 $headers['Cookie'] = implode('; ', $cookies);
137 * Parse all cookies from a response and attach them to the response
139 * @var Requests_Response $response
141 public function before_redirect_check(Requests_Response &$return) {
142 $cookies = Requests_Cookie::parseFromHeaders($return->headers);
143 $this->cookies = array_merge($this->cookies, $cookies);
144 $return->cookies = $this;