|
<?php |
|
namespace Example\Shared; |
|
|
|
trait BehaviourOfIterable |
|
{ |
|
/** |
|
* @return Iterable instance of the iterable with the provided data and order |
|
*/ |
|
abstract protected function createIterable(array $data, array $order); |
|
|
|
/** |
|
* @param int $id a unique identifier for the item |
|
* @return array valid item array for use in $data |
|
*/ |
|
abstract protected function createIterableItem($id = 0); |
|
|
|
/** |
|
* Extract the unique identifier from an item instance |
|
* This will be used to compare to items created via createIterableItem |
|
* |
|
* @return int |
|
*/ |
|
abstract protected function getIterableItemIdentifier($item); |
|
|
|
|
|
/** |
|
* @return string class name of item instances |
|
*/ |
|
abstract protected function getIterableItemClassName(); |
|
|
|
public function test_empty_collection_has_zero_length() |
|
{ |
|
$collection = $this->createIterable([], []); |
|
$this->assertEquals(0, $collection->length()); |
|
} |
|
|
|
public function test_length_reports_collection_length() |
|
{ |
|
$collection = $this->createIterable( |
|
[ |
|
$this->createIterableItem(), |
|
$this->createIterableItem(), |
|
$this->createIterableItem(), |
|
], |
|
[0, 1, 2] |
|
); |
|
$this->assertEquals(3, $collection->length()); |
|
} |
|
|
|
public function test_empty_collection_items_doesnt_iterate() |
|
{ |
|
$collection = $this->createIterable([], []); |
|
foreach ($collection->items() as $item) { |
|
$this->fail('Did not expect items() to iterate'); |
|
} |
|
} |
|
|
|
public function test_collection_items_have_correct_type() |
|
{ |
|
$collection = $this->createIterable( |
|
[ |
|
$this->createIterableItem(), |
|
$this->createIterableItem(), |
|
$this->createIterableItem(), |
|
], |
|
[0, 1, 2] |
|
); |
|
foreach ($collection->items() as $item) { |
|
$this->assertInstanceOf($this->getIterableItemClassName(), $item); |
|
} |
|
} |
|
|
|
public function test_collection_items_iterates_in_order() |
|
{ |
|
$collection = $this->createIterable( |
|
[ |
|
1 => $this->createIterableItem(1), |
|
2 => $this->createIterableItem(2), |
|
3 => $this->createIterableItem(3), |
|
], |
|
$order = [2, 3, 1] |
|
); |
|
$i = 0; |
|
foreach ($collection->items() as $item) { |
|
$this->assertEquals( |
|
$order[$i++], |
|
$this->getIterableItemIdentifier($item) |
|
); |
|
} |
|
} |
|
|
|
} |