From da0bd3f09442e0b92a43bb97763283fd0dcda411 Mon Sep 17 00:00:00 2001 From: Luke Visinoni Date: Tue, 24 Jul 2018 22:29:27 -0700 Subject: [PATCH] getRow now accepts negative offsets (although performance won't be as good when using negative offsets since the entire set has to be pulled) --- src/CSVelte/Reader.php | 3 +++ tests/CSVelte/ReaderTest.php | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/CSVelte/Reader.php b/src/CSVelte/Reader.php index 93f74f8..aa63931 100644 --- a/src/CSVelte/Reader.php +++ b/src/CSVelte/Reader.php @@ -106,6 +106,9 @@ public function getDialect() public function getRow($offset = null) { if (!is_null($offset)) { + if ($offset < 0) { + return collect($this->toArray())->getValueAt($offset); + } foreach ($this as $key => $row) { if ($key === $offset) { return $row; diff --git a/tests/CSVelte/ReaderTest.php b/tests/CSVelte/ReaderTest.php index acbad4b..1d9b06c 100644 --- a/tests/CSVelte/ReaderTest.php +++ b/tests/CSVelte/ReaderTest.php @@ -162,6 +162,39 @@ public function testGetRowUsingOffsetReturnsRowAtGivenOffset() ], $reader->getRow(25)); } + public function testGetRowUsingNegativeOffsetReturnsRowAtGivenOffset() + { + $source = to_stream(fopen($this->getFilePathFor('commaNewlineHeader'), 'r+')); + $reader = new Reader($source); + $this->assertSame([ + "Bank Name" => "Vantage Point Bank", + "City" => "Horsham", + "ST" => "PA", + "CERT" => "58531", + "Acquiring Institution" => "First Choice Bank", + "Closing Date" => "28-Feb-14", + "Updated Date" => "3-Mar-15" + ], $reader->getRow(-5)); + $this->assertSame([ + "Bank Name" => "Valley Bank", + "City" => "Moline", + "ST" => "IL", + "CERT" => "10450", + "Acquiring Institution" => "Great Southern Bank", + "Closing Date" => "20-Jun-14", + "Updated Date" => "26-Jun-15" + ], $reader->getRow(-10)); + $this->assertSame([ + "Bank Name" => "The Bank of Georgia", + "City" => "Peachtree City", + "ST" => "GA", + "CERT" => "35259", + "Acquiring Institution" => "Fidelity Bank", + "Closing Date" => "2-Oct-15", + "Updated Date" => "13-Apr-16" + ], $reader->getRow(-25)); + } + public function testGetColumnReturnsColumn() { $source = to_stream(fopen($this->getFilePathFor('commaNewlineHeader'), 'r+'));