diff --git a/src/Traits/Collection/MainTrait.php b/src/Traits/Collection/MainTrait.php index 8835a2d..8c401fa 100644 --- a/src/Traits/Collection/MainTrait.php +++ b/src/Traits/Collection/MainTrait.php @@ -188,6 +188,21 @@ trait MainTrait return Arrays::getLastElement($this->elements); } + /** + * Returns element with given index + * + * @param mixed $index Index / key of the element + * @return mixed|null + */ + public function getByIndex($index) + { + if (isset($this->elements[$index])) { + return $this->elements[$index]; + } + + return null; + } + /** * Returns representation of object as array * diff --git a/tests/Collection/CollectionTest.php b/tests/Collection/CollectionTest.php index 5b789c7..37e9be2 100644 --- a/tests/Collection/CollectionTest.php +++ b/tests/Collection/CollectionTest.php @@ -327,6 +327,19 @@ class CollectionTest extends BaseTestCase static::assertMethodVisibilityAndArguments(Collection::class, 'exists', OopVisibilityType::IS_PRIVATE, 1, 1); } + /** + * @param string $description Description of test + * @param Collection $collection Collection to search for element with given index + * @param mixed $index Index / key of the element + * @param mixed $expected Expected element with given index + * + * @dataProvider provideElementGetByIndex + */ + public function testGetByIndex($description, Collection $collection, $index, $expected) + { + static::assertEquals($expected, $collection->getByIndex($index), $description); + } + /** * Provides element to add to collection * @@ -408,6 +421,73 @@ class CollectionTest extends BaseTestCase ]; } + public function provideElementGetByIndex() + { + yield[ + 'An empty collection and empty index', + new Collection(), + '', + null, + ]; + + yield[ + 'An empty collection and non-empty index', + new Collection(), + 'test', + null, + ]; + + yield[ + 'Non-empty collection and not existing index', + new Collection([ + 'lorem' => 'ipsum', + 'dolor' => 'sit', + ]), + 'test', + null, + ]; + + yield[ + 'Collection with existing index', + new Collection([ + 'lorem' => 'ipsum', + 'dolor' => 'sit', + ]), + 'lorem', + 'ipsum', + ]; + + yield[ + 'Collection with existing index (collection of arrays)', + new Collection([ + [ + 'lorem', + 'ipsum', + ], + [ + 'dolor', + 'sit', + ], + ]), + 0, + [ + 'lorem', + 'ipsum', + ], + ]; + + yield[ + 'Collection with existing index (collection of objects)', + new Collection([ + 'x' => new \DateTime(), + 'y' => new \DateTime('2001-01-01'), + 'z' => new \DateTime('yesterday'), + ]), + 'y', + new \DateTime('2001-01-01'), + ]; + } + /** * {@inheritdoc} */