diff --git a/lib/Util/CaseInsensitiveArray.php b/lib/Util/CaseInsensitiveArray.php index 02c6f26da..d4ec37659 100644 --- a/lib/Util/CaseInsensitiveArray.php +++ b/lib/Util/CaseInsensitiveArray.php @@ -2,8 +2,6 @@ namespace Stripe\Util; -use ArrayAccess; - /** * CaseInsensitiveArray is an array-like class that ignores case for keys. * @@ -14,13 +12,23 @@ * In the context of stripe-php, this is useful because the API will return headers with different * case depending on whether HTTP/2 is used or not (with HTTP/2, headers are always in lowercase). */ -class CaseInsensitiveArray implements ArrayAccess +class CaseInsensitiveArray implements \ArrayAccess, \Countable, \IteratorAggregate { - private $container = array(); + private $container = []; + + public function __construct($initial_array = []) + { + $this->container = array_change_key_case($initial_array, CASE_LOWER); + } + + public function count() + { + return count($this->container); + } - public function __construct($initial_array = array()) + public function getIterator() { - $this->container = array_map("strtolower", $initial_array); + return new \ArrayIterator($this->container); } public function offsetSet($offset, $value) diff --git a/tests/Stripe/Util/CaseInsensitiveArrayTest.php b/tests/Stripe/Util/CaseInsensitiveArrayTest.php new file mode 100644 index 000000000..5bfb21ad6 --- /dev/null +++ b/tests/Stripe/Util/CaseInsensitiveArrayTest.php @@ -0,0 +1,46 @@ + "1", "TWO" => "2"]); + + $arr["thrEE"] = "3"; + + $this->assertSame("1", $arr["one"]); + $this->assertSame("1", $arr["One"]); + $this->assertSame("1", $arr["ONE"]); + + $this->assertSame("2", $arr["two"]); + $this->assertSame("2", $arr["twO"]); + $this->assertSame("2", $arr["TWO"]); + + $this->assertSame("3", $arr["three"]); + $this->assertSame("3", $arr["ThReE"]); + $this->assertSame("3", $arr["THREE"]); + } + + public function testCount() + { + $arr = new CaseInsensitiveArray(["One" => "1", "TWO" => "2"]); + + $this->assertSame(2, count($arr)); + } + + public function testIterable() + { + $arr = new CaseInsensitiveArray(["One" => "1", "TWO" => "2"]); + + $seen = []; + + foreach ($arr as $k => $v) { + $seen[$k] = $v; + } + + $this->assertSame("1", $seen["one"]); + $this->assertSame("2", $seen["two"]); + } +}