Skip to content

Commit

Permalink
Merge pull request #736 from stripe/ob-fix-735
Browse files Browse the repository at this point in the history
Make CaseInsensitiveArray countable and traversable
  • Loading branch information
ob-stripe authored Sep 13, 2019
2 parents c3eff79 + 2ccc0b1 commit 384f1d2
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 6 deletions.
20 changes: 14 additions & 6 deletions lib/Util/CaseInsensitiveArray.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

namespace Stripe\Util;

use ArrayAccess;

/**
* CaseInsensitiveArray is an array-like class that ignores case for keys.
*
Expand All @@ -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)
Expand Down
46 changes: 46 additions & 0 deletions tests/Stripe/Util/CaseInsensitiveArrayTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace Stripe\Util;

class CaseInsensitiveArrayTest extends \Stripe\TestCase
{
public function testArrayAccess()
{
$arr = new CaseInsensitiveArray(["One" => "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"]);
}
}

0 comments on commit 384f1d2

Please sign in to comment.