Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
95.65% |
22 / 23 |
|
66.67% |
2 / 3 |
CRAP | |
0.00% |
0 / 1 |
| CookieJar | |
95.65% |
22 / 23 |
|
66.67% |
2 / 3 |
9 | |
0.00% |
0 / 1 |
| setCookie | |
75.00% |
3 / 4 |
|
0.00% |
0 / 1 |
2.06 | |||
| serializeToHttpRequest | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 | |||
| parseCookieResponseHeader | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
4 | |||
| 1 | <?php |
| 2 | /** |
| 3 | * @license GPL-2.0-or-later |
| 4 | * @file |
| 5 | * @ingroup HTTP |
| 6 | */ |
| 7 | |
| 8 | /** |
| 9 | * Cookie jar to use with MWHttpRequest. Does not handle cookie unsetting. |
| 10 | */ |
| 11 | class CookieJar { |
| 12 | |
| 13 | /** @var Cookie[] */ |
| 14 | private array $cookie = []; |
| 15 | |
| 16 | /** |
| 17 | * Set a cookie in the cookie jar. Make sure only one cookie per-name exists. |
| 18 | * @see Cookie::set() |
| 19 | * @param string $name |
| 20 | * @param string $value |
| 21 | * @param string[] $attr |
| 22 | */ |
| 23 | public function setCookie( string $name, string $value, array $attr ): void { |
| 24 | /* cookies: case insensitive, so this should work. |
| 25 | * We'll still send the cookies back in the same case we got them, though. |
| 26 | */ |
| 27 | $index = strtoupper( $name ); |
| 28 | |
| 29 | if ( isset( $this->cookie[$index] ) ) { |
| 30 | $this->cookie[$index]->set( $value, $attr ); |
| 31 | } else { |
| 32 | $this->cookie[$index] = new Cookie( $name, $value, $attr ); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * @see Cookie::serializeToHttpRequest |
| 38 | */ |
| 39 | public function serializeToHttpRequest( string $path, string $domain ): string { |
| 40 | $cookies = []; |
| 41 | |
| 42 | foreach ( $this->cookie as $c ) { |
| 43 | $serialized = $c->serializeToHttpRequest( $path, $domain ); |
| 44 | if ( $serialized ) { |
| 45 | $cookies[] = $serialized; |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | return implode( '; ', $cookies ); |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Parse the content of an Set-Cookie HTTP Response header. |
| 54 | * |
| 55 | * @param string $cookie |
| 56 | * @param string $domain Cookie's domain |
| 57 | */ |
| 58 | public function parseCookieResponseHeader( string $cookie, string $domain ): void { |
| 59 | $bit = array_map( 'trim', explode( ';', $cookie ) ); |
| 60 | |
| 61 | $parts = explode( '=', array_shift( $bit ), 2 ); |
| 62 | $name = $parts[0]; |
| 63 | $value = $parts[1] ?? ''; |
| 64 | |
| 65 | $attr = []; |
| 66 | foreach ( $bit as $piece ) { |
| 67 | $parts = explode( '=', $piece, 2 ); |
| 68 | $attr[ strtolower( $parts[0] ) ] = $parts[1] ?? true; |
| 69 | } |
| 70 | |
| 71 | if ( !isset( $attr['domain'] ) ) { |
| 72 | $attr['domain'] = $domain; |
| 73 | } elseif ( !Cookie::validateCookieDomain( $attr['domain'], $domain ) ) { |
| 74 | return; |
| 75 | } |
| 76 | |
| 77 | $this->setCookie( $name, $value, $attr ); |
| 78 | } |
| 79 | |
| 80 | } |