From 88672cc6b453bb708525390247f206036f2982f2 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Mon, 25 Mar 2024 11:09:57 +0100 Subject: [PATCH] [PHP 8.4] Fixes for implicit nullability deprecation (#865) Co-authored-by: jrfnl --- src/Cookie.php | 8 +++++++- tests/CookieTest.php | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/Cookie.php b/src/Cookie.php index 6f971d6db..2cc821d64 100644 --- a/src/Cookie.php +++ b/src/Cookie.php @@ -470,13 +470,19 @@ public static function parse($cookie_header, $name = '', $reference_time = null) * @param \WpOrg\Requests\Iri|null $origin URI for comparing cookie origins * @param int|null $time Reference time for expiration calculation * @return array + * + * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $origin argument is not null or an instance of the Iri class. */ - public static function parse_from_headers(Headers $headers, Iri $origin = null, $time = null) { + public static function parse_from_headers(Headers $headers, $origin = null, $time = null) { $cookie_headers = $headers->getValues('Set-Cookie'); if (empty($cookie_headers)) { return []; } + if ($origin !== null && !($origin instanceof Iri)) { + throw InvalidArgument::create(2, '$origin', Iri::class . ' or null', gettype($origin)); + } + $cookies = []; foreach ($cookie_headers as $header) { $parsed = self::parse($header, '', $time); diff --git a/tests/CookieTest.php b/tests/CookieTest.php index eb476d1dc..0a27b2757 100644 --- a/tests/CookieTest.php +++ b/tests/CookieTest.php @@ -4,6 +4,7 @@ use DateTime; use EmptyIterator; +use stdClass; use WpOrg\Requests\Cookie; use WpOrg\Requests\Exception\InvalidArgument; use WpOrg\Requests\Iri; @@ -807,4 +808,39 @@ public function testParseFromHeadersInvalidReferenceTime() { Cookie::parse_from_headers($headers, $origin, 'now'); } + + /** + * Verify parsing of cookies fails with an exception if the $origin parameter is passed anything but `null` + * or an instance of Iri. + * + * @dataProvider dataParseFromHeadersInvalidOrigin + * + * @covers ::parse_from_headers + * + * @param mixed $input Invalid parameter input. + * + * @return void + */ + public function testParseFromHeadersInvalidOrigin($input) { + $this->expectException(InvalidArgument::class); + $this->expectExceptionMessage('Argument #2 ($origin) must be of type WpOrg\Requests\Iri or null'); + + $headers = new Headers(); + $headers['Set-Cookie'] = 'name=value'; + + Cookie::parse_from_headers($headers, $input); + } + + /** + * Data Provider. + * + * @return array + */ + public static function dataParseFromHeadersInvalidOrigin() { + return [ + 'falseg' => [false], + 'string' => ['something'], + 'stdClass' => [new stdClass()], + ]; + } }