Created
September 10, 2021 16:28
-
-
Save JeffreyWay/5f874ee8a658566f858ed90dcd275e7b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use ArrayAccess; | |
use ArrayIterator; | |
use Countable; | |
use IteratorAggregate; | |
class Collection implements Countable, ArrayAccess, IteratorAggregate | |
{ | |
public function __construct(protected array $items) | |
{ | |
// | |
} | |
public static function make(array $items) | |
{ | |
return new static($items); | |
} | |
public function count() | |
{ | |
return count($this->items); | |
} | |
public function offsetExists($offset) | |
{ | |
return isset($this->items[$offset]); | |
} | |
public function offsetGet($offset) | |
{ | |
return $this->items[$offset]; | |
} | |
public function offsetSet($offset, $value) | |
{ | |
if (is_null($offset)) { | |
$this->items[] = $value; | |
} else { | |
$this->items[$offset] = $value; | |
} | |
} | |
public function offsetUnset($offset) | |
{ | |
unset($this->items[$offset]); | |
} | |
public function getIterator() | |
{ | |
return new ArrayIterator($this->items); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tests; | |
use App\Collection; | |
use IteratorAggregate; | |
use PHPUnit\Framework\TestCase; | |
class CollectionTest extends TestCase | |
{ | |
/** @test */ | |
function it_can_be_counted() | |
{ | |
$items = ['one', 'two', 'three']; | |
$this->assertCount(3, Collection::make($items)); | |
} | |
/** @test */ | |
function it_mimics_an_array() | |
{ | |
$items = ['one', 'two', 'three']; | |
$collection = Collection::make($items); | |
$this->assertEquals('one', $collection[0]); | |
$this->assertEquals('two', $collection[1]); | |
$this->assertEquals('three', $collection[2]); | |
} | |
/** @test */ | |
function it_can_be_iterated() | |
{ | |
$items = ['one', 'two', 'three']; | |
$collection = Collection::make($items); | |
$this->assertInstanceOf(IteratorAggregate::class, $collection); | |
foreach ($collection as $index => $item) { | |
$this->assertEquals($items[$index], $item); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment