From 9dd03308c49233c9288532b27f617ae34487bbfe Mon Sep 17 00:00:00 2001 From: Joseph Bielawski Date: Wed, 4 Oct 2023 20:35:21 +0200 Subject: [PATCH] Fixed `Cast` expression to handle `null` as first (#515) --- .../ETL/Row/Reference/Expression/Cast.php | 4 ++++ .../Row/Reference/Expression/CastTest.php | 19 +++++++++++-------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/core/etl/src/Flow/ETL/Row/Reference/Expression/Cast.php b/src/core/etl/src/Flow/ETL/Row/Reference/Expression/Cast.php index a62b85206..f1d748cf0 100644 --- a/src/core/etl/src/Flow/ETL/Row/Reference/Expression/Cast.php +++ b/src/core/etl/src/Flow/ETL/Row/Reference/Expression/Cast.php @@ -25,6 +25,10 @@ public function eval(Row $row) : mixed /** @psalm-suppress MixedAssignment */ $value = $this->ref->eval($row); + if (null === $value) { + return null; + } + return match (\mb_strtolower($this->type)) { 'datetime' => match (\gettype($value)) { 'string' => new \DateTimeImmutable($value), diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Row/Reference/Expression/CastTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Row/Reference/Expression/CastTest.php index a73a97fbb..5d2614774 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Row/Reference/Expression/CastTest.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Row/Reference/Expression/CastTest.php @@ -19,6 +19,7 @@ public static function cast_provider() : array $xml->loadXML($xmlString = 'bar'); return [ + 'invalid' => [null, 'int', null], 'int' => ['1', 'int', 1], 'integer' => ['1', 'integer', 1], 'float' => ['1', 'float', 1.0], @@ -42,14 +43,16 @@ public static function cast_provider() : array */ public function test_cast(mixed $from, string $to, mixed $expected) : void { - $this->assertEquals( - $expected, - ref('value')->cast($to)->eval(Row::create((new NativeEntryFactory())->create('value', $from))) - ); - $this->assertEquals( - $expected, - cast(ref('value'), $to)->eval(Row::create((new NativeEntryFactory())->create('value', $from))) - ); + $resultRefCast = ref('value')->cast($to)->eval(Row::create((new NativeEntryFactory())->create('value', $from))); + $resultCastRef = cast(ref('value'), $to)->eval(Row::create((new NativeEntryFactory())->create('value', $from))); + + if (\is_object($expected)) { + $this->assertEquals($expected, $resultRefCast); + $this->assertEquals($expected, $resultCastRef); + } else { + $this->assertSame($expected, $resultRefCast); + $this->assertSame($expected, $resultCastRef); + } } public function test_casting_integer_to_xml() : void