Skip to content

Commit

Permalink
Merge pull request #48 from schmittjoh/array-fix
Browse files Browse the repository at this point in the history
[1.5] Fix ArrayAccess on `fromArraysValue`
  • Loading branch information
GrahamCampbell authored Dec 11, 2019
2 parents 2ba2586 + e315ec5 commit 77fbb6d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
7 changes: 4 additions & 3 deletions src/PhpOption/Option.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

namespace PhpOption;

use ArrayAccess;
use IteratorAggregate;

/**
Expand Down Expand Up @@ -57,14 +58,14 @@ public static function fromValue($value, $noneValue = null)
*
* Otherwise, Some is returned wrapping the value at the given key.
*
* @param mixed $array a potential array value
* @param string $key the key to check
* @param mixed $array A potential array or \ArrayAccess value.
* @param string $key The key to check.
*
* @return Option
*/
public static function fromArraysValue($array, $key)
{
if (!is_array($array) || !isset($array[$key])) {
if (!(is_array($array) || $array instanceof ArrayAccess) || !isset($array[$key])) {
return None::create();
}

Expand Down
31 changes: 30 additions & 1 deletion tests/PhpOption/Tests/OptionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ public function testFromArraysValue()
$this->assertEquals(None::create(), Option::fromArraysValue(array('foo' => 'bar'), 'baz'));
$this->assertEquals(None::create(), Option::fromArraysValue(array('foo' => null), 'foo'));
$this->assertEquals(new Some('foo'), Option::fromArraysValue(array('foo' => 'foo'), 'foo'));

$object = new SomeArrayObject();
$object['foo'] = 'foo';
$this->assertEquals(new Some('foo'), Option::fromArraysValue($object, 'foo'));
}

public function testFromReturn()
Expand Down Expand Up @@ -78,4 +82,29 @@ public function testOrElseWithMultipleAlternatives()

$this->assertEquals('foo', $a->orElse($returns)->orElse($throws)->get());
}
}
}

class SomeArrayObject implements \ArrayAccess
{
private $data = array();

public function offsetExists($offset)
{
return isset($this->data[$offset]);
}

public function offsetGet($offset)
{
return $this->data[$offset];
}

public function offsetSet($offset, $value)
{
$this->data[$offset] = $value;
}

public function offsetUnset($offset)
{
unset($this->data[$offset]);
}
}

0 comments on commit 77fbb6d

Please sign in to comment.