Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make CaseInsensitiveArray countable and traversable #736

Merged
merged 1 commit into from
Sep 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"]);
}
}