From be62327509875e68a83d7d40590013d2c4e800be Mon Sep 17 00:00:00 2001 From: Yuri Kuznetsov Date: Tue, 8 Feb 2022 17:18:14 +0200 Subject: [PATCH] string split function --- .../Functions/StringGroup/SplitType.php | 65 +++++++++++++++++++ .../Espo/Resources/metadata/app/formula.json | 5 ++ .../unit/Espo/Core/Formula/EvaluatorTest.php | 30 +++++++++ 3 files changed, 100 insertions(+) create mode 100644 application/Espo/Core/Formula/Functions/StringGroup/SplitType.php diff --git a/application/Espo/Core/Formula/Functions/StringGroup/SplitType.php b/application/Espo/Core/Formula/Functions/StringGroup/SplitType.php new file mode 100644 index 0000000000..b0a3030c48 --- /dev/null +++ b/application/Espo/Core/Formula/Functions/StringGroup/SplitType.php @@ -0,0 +1,65 @@ +evaluate($args); + + if (count($evaluatedArgs) < 2) { + $this->throwTooFewArguments(2); + } + + $string = $evaluatedArgs[0] ?? ''; + $separator = $evaluatedArgs[1]; + + if (!is_string($string)) { + $this->throwBadArgumentType(1, 'string'); + } + + if (!is_string($separator)) { + $this->throwBadArgumentType(2, 'string'); + } + + if ($separator === '') { + return mb_str_split($string); + } + + return explode($separator, $string); + } +} diff --git a/application/Espo/Resources/metadata/app/formula.json b/application/Espo/Resources/metadata/app/formula.json index 0ca4b5136c..94d235b769 100644 --- a/application/Espo/Resources/metadata/app/formula.json +++ b/application/Espo/Resources/metadata/app/formula.json @@ -82,6 +82,11 @@ "insertText": "string\\replace(STRING, SEARCH, REPLACE)", "returnType": "string" }, + { + "name": "string\\split", + "insertText": "string\\split(STRING, SEPARATOR)", + "returnType": "string[]" + }, { "name": "datetime\\today", "insertText": "datetime\\today()", diff --git a/tests/unit/Espo/Core/Formula/EvaluatorTest.php b/tests/unit/Espo/Core/Formula/EvaluatorTest.php index 1591fc93c9..3d1aecd5e2 100644 --- a/tests/unit/Espo/Core/Formula/EvaluatorTest.php +++ b/tests/unit/Espo/Core/Formula/EvaluatorTest.php @@ -634,4 +634,34 @@ class EvaluatorTest extends \PHPUnit\Framework\TestCase $this->evaluator->process($expression, null); } + + public function testStringSplit1(): void + { + $expression = "string\\split('1 2 3', ' ')"; + + $this->assertEquals( + ['1', '2', '3'], + $this->evaluator->process($expression, null) + ); + } + + public function testStringSplit2(): void + { + $expression = "string\\split(null, '')"; + + $this->assertEquals( + [], + $this->evaluator->process($expression, null) + ); + } + + public function testStringSplit3(): void + { + $expression = "string\\split('12', '')"; + + $this->assertEquals( + ['1', '2'], + $this->evaluator->process($expression, null) + ); + } }