Skip to content

Instantly share code, notes, and snippets.

@jakzal
Last active December 19, 2023 11:08
Show Gist options
  • Save jakzal/5555451 to your computer and use it in GitHub Desktop.
Save jakzal/5555451 to your computer and use it in GitHub Desktop.
Mocking ArrayAccess with prophecy in phpspec
<?php
class MyThing
{
private $myArray = null;
public function __construct($myArray)
{
$this->myArray = $myArray;
}
public function getFromArray($name)
{
return $this->myArray[$name];
}
public function __call($method, $arguments)
{
$field = lcfirst(substr($method, 3));
return $this->getFromArray($field);
}
public function __get($name)
{
return $this->getFromArray($name);
}
}
<?php
namespace spec;
use PhpSpec\ObjectBehavior;
class MyThingSpec extends ObjectBehavior
{
function let(\ArrayAccess $myArray)
{
$this->beConstructedWith($myArray);
}
function it_retrieves_my_array_details(\ArrayAccess $myArray)
{
$myArray->offsetGet('foo')->shouldBeCalled()->willReturn('bar');
$this->getFromArray('foo')->shouldReturn('bar');
}
function it_retrieves_my_array_details_with_a_magic_call(\ArrayAccess $myArray)
{
$myArray->offsetGet('foo')->shouldBeCalled()->willReturn('bar');
$this->getFoo()->shouldReturn('bar');
}
function it_retrieves_my_array_details_by_accessing_a_property(\ArrayAccess $myArray)
{
$myArray->offsetGet('foo')->shouldBeCalled()->willReturn('bar');
$this->foo->shouldReturn('bar');
}
}
@martcor
Copy link

martcor commented Dec 18, 2023

Awesome! I think this should be added to the official documentation somewhere!

The \ArrayAccess can't be used in all situations as described in official documentation.

@jakzal
Copy link
Author

jakzal commented Dec 19, 2023

@martcor in retrospect, I would not mock ArrayAccess nor any native language behaviour. Just create the thing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment