From e5ede9190efac05b1714b6d8f27ab1d4a96e7fa5 Mon Sep 17 00:00:00 2001 From: f-lapinski Date: Mon, 17 Feb 2025 09:15:37 +0100 Subject: [PATCH] Add StringBefore function with test --- .../Flow/ETL/Function/ScalarFunctionChain.php | 5 ++ .../src/Flow/ETL/Function/StringBefore.php | 39 ++++++++++++ .../Tests/Unit/Function/StringBeforeTest.php | 60 +++++++++++++++++++ 3 files changed, 104 insertions(+) create mode 100644 src/core/etl/src/Flow/ETL/Function/StringBefore.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Function/StringBeforeTest.php diff --git a/src/core/etl/src/Flow/ETL/Function/ScalarFunctionChain.php b/src/core/etl/src/Flow/ETL/Function/ScalarFunctionChain.php index a89163b56..9af9327f8 100644 --- a/src/core/etl/src/Flow/ETL/Function/ScalarFunctionChain.php +++ b/src/core/etl/src/Flow/ETL/Function/ScalarFunctionChain.php @@ -482,6 +482,11 @@ public function startsWith(ScalarFunction|string $needle) : self return new StartsWith($this, $needle); } + public function stringBefore(ScalarFunction|string $needle, ScalarFunction|bool $includeNeedle = false) : self + { + return new StringBefore($this, $needle, $includeNeedle); + } + public function stringFold() : self { return new StringFold($this); diff --git a/src/core/etl/src/Flow/ETL/Function/StringBefore.php b/src/core/etl/src/Flow/ETL/Function/StringBefore.php new file mode 100644 index 000000000..4ec7f80b9 --- /dev/null +++ b/src/core/etl/src/Flow/ETL/Function/StringBefore.php @@ -0,0 +1,39 @@ +string))->asString($row); + $needle = (new Parameter($this->needle))->as($row, type_string(), type_list(type_string())); + $includeNeedle = (new Parameter($this->includeNeedle))->asBoolean($row); + + if ($string === null) { + return null; + } + + return u($string)->before($needle, $includeNeedle)->toString(); + } + + public function returns() : Type + { + return type_string(); + } +} diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Function/StringBeforeTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Function/StringBeforeTest.php new file mode 100644 index 000000000..7980bc65b --- /dev/null +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Function/StringBeforeTest.php @@ -0,0 +1,60 @@ +returns(); + + self::assertInstanceOf(Type::class, $returnType); + + self::assertTrue($returnType->isEqual(type_string())); + } + + public function test_string_before() : void + { + self::assertSame( + 'hello ', + ref('str')->stringBefore(ref('needle'))->eval( + row( + str_entry('str', 'hello world'), + str_entry('needle', 'world') + ) + ) + ); + + self::assertSame( + 'hell', + ref('str')->stringBefore(ref('needle'))->eval( + row( + str_entry('str', 'hello world'), + str_entry('needle', 'o') + ) + ) + ); + } + + public function test_string_before_including_needle() : void + { + self::assertSame( + 'hello', + ref('str')->stringBefore(ref('needle'), includeNeedle: true)->eval( + row( + str_entry('str', 'hello world'), + str_entry('needle', 'o') + ) + ) + ); + } +}