Skip to content

Instantly share code, notes, and snippets.

@peterjmit peterjmit/0-usage.php
Last active Dec 27, 2015

Embed
What would you like to do?
<?php
$collection = new Collection();
$collection->add('item');
$collection->add('another item');
$collection->add('item');
/*
What would you expect here? Probably a count of 3...
or if your collection only tracked unique items, you would expect 2.
This is the behaviour that you are defining and therefore it is
important to test it!
*/
echo count($collection);
// or
echo $collection->count();
<?php
class Collection implements \Countable
{
private $items;
public function __construct(array $items = [])
{
$this->items = $items;
}
public function add($item)
{
$this->items[] = $item;
}
public function count()
{
return count($this->items);
}
}
<?php
namespace spec;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class CollectionSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Collection');
}
function it_implements_countable()
{
$this->shouldImplement('Countable');
}
function it_counts_its_items()
{
$this->add('item 1');
$this->add('item 2');
$this->add('item 3');
$this->count()->shouldReturn(3);
}
// Using our first attempt at implementing a \Countable Collection
// (Collection1.php) this spec will fail...
function it_should_only_count_unique_items()
{
$this->add('item');
$this->add('item');
$this->add('item');
$this->count()->shouldReturn(1);
}
}
<?php
class Collection implements \Countable
{
private $items;
public function __construct(array $items = [])
{
$this->items = $items;
}
public function add($item)
{
if (!in_array($item, $this->items)) {
$this->items[] = $item;
}
}
public function count()
{
return count(array_unique($this->items));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.