From 4869a792fdcc2abbb602313cf40f2b1381943631 Mon Sep 17 00:00:00 2001 From: Leonardo Marquine Date: Mon, 5 Nov 2018 13:46:17 -0200 Subject: [PATCH] Fix rename columns transformer --- src/Transformers/RenameColumns.php | 22 +++++++++++----------- tests/Transformers/RenameColumnsTest.php | 13 ++++++++----- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/src/Transformers/RenameColumns.php b/src/Transformers/RenameColumns.php index 812b4ee..eba6926 100644 --- a/src/Transformers/RenameColumns.php +++ b/src/Transformers/RenameColumns.php @@ -2,6 +2,8 @@ namespace Marquine\Etl\Transformers; +use Marquine\Etl\Row; + class RenameColumns extends Transformer { /** @@ -21,19 +23,17 @@ class RenameColumns extends Transformer ]; /** - * Get the transformer handler. + * Transform the given row. * - * @return callable + * @param \Marquine\Etl\Row $row + * @return void */ - public function transform() + public function transform(Row $row) { - return function ($row) { - foreach ($this->columns as $old => $new) { - $row[$new] = $row[$old]; - unset($row[$old]); - } - - return $row; - }; + foreach ($this->columns as $old => $new) { + $value = $row->get($old); + $row->remove($old); + $row->set($new, $value); + } } } diff --git a/tests/Transformers/RenameColumnsTest.php b/tests/Transformers/RenameColumnsTest.php index 1abee3d..9a07d82 100644 --- a/tests/Transformers/RenameColumnsTest.php +++ b/tests/Transformers/RenameColumnsTest.php @@ -3,6 +3,7 @@ namespace Tests\Transformers; use Tests\TestCase; +use Marquine\Etl\Row; use Marquine\Etl\Transformers\RenameColumns; class RenameColumnsTest extends TestCase @@ -11,19 +12,21 @@ class RenameColumnsTest extends TestCase public function rename_column() { $data = [ - ['id' => '1', 'name' => 'John Doe', 'email_address' => 'johndoe@email.com'], - ['id' => '2', 'name' => 'Jane Doe', 'email_address' => 'janedoe@email.com'], + new Row(['id' => '1', 'name' => 'John Doe', 'email_address' => 'johndoe@email.com']), + new Row(['id' => '2', 'name' => 'Jane Doe', 'email_address' => 'janedoe@email.com']), ]; $expected = [ - ['id' => '1', 'name' => 'John Doe', 'email' => 'johndoe@email.com'], - ['id' => '2', 'name' => 'Jane Doe', 'email' => 'janedoe@email.com'], + new Row(['id' => '1', 'name' => 'John Doe', 'email' => 'johndoe@email.com']), + new Row(['id' => '2', 'name' => 'Jane Doe', 'email' => 'janedoe@email.com']), ]; $transformer = new RenameColumns; $transformer->options(['columns' => ['email_address' => 'email']]); - $this->assertEquals($expected, array_map($transformer->transform(), $data)); + array_map([$transformer, 'transform'], $data); + + $this->assertEquals($expected, $data); } }