EspoCRM – Open Source CRM Application
PHP calendarcontactscrmcrm-platformcrm-systemcustomer-portalcustomer-supportcustomizabledocumentsemail-marketingkanbanleadsopen-sourcephpplatformsales-automationsingle-page-applicationsupport
formula: key value access
Yuri Kuznetsov7763ddb80275
diff --git a/application/Espo/Core/Formula/Functions/VariableGetValueByKeyType.php b/application/Espo/Core/Formula/Functions/VariableGetValueByKeyType.phpnew file mode 100644index 0000000000..60fe30bb5c--- /dev/null+++ b/application/Espo/Core/Formula/Functions/VariableGetValueByKeyType.php@@ -0,0 +1,98 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2025 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Core\Formula\Functions;++use Espo\Core\Formula\ArgumentList;+use Espo\Core\Formula\Exceptions\Error;+use stdClass;++/**+ * @noinspection PhpUnused+ */+class VariableGetValueByKeyType extends BaseFunction+{+ public function process(ArgumentList $args)+ {+ if (count($args) < 2) {+ $this->throwTooFewArguments();+ }++ $name = $this->evaluate($args[0]);+ $key = $this->evaluate($args[1]);++ if (!is_string($name)) {+ $this->throwBadArgumentValue(1, 'string');+ }++ if (!property_exists($this->getVariables(), $name)) {+ throw new Error("Cannot access by key of non-existing variable.");+ }++ $reference =& $this->getVariables()->$name;++ if (!is_array($reference) && !$reference instanceof stdClass) {+ throw new Error("Cannot access by key of variable that is non-array and non-object.");+ }++ if (is_array($reference)) {+ if (!is_int($key)) {+ throw new Error("Cannot get array item value by non-integer key.");+ }++ if ($key < 0) {+ throw new Error("Cannot get array item value by key that is less than zero.");+ }++ if ($key > count($reference) - 1) {+ throw new Error("Cannot get array item value by key that is out of array end.");+ }++ if (!array_key_exists($key, $reference)) {+ throw new Error("Cannot get array item value by non-existent key.");+ }++ return $reference[$key];+ }++ if (!is_string($key)) {+ throw new Error("Cannot get object item value by non-string key.");+ }++ if ($key === '') {+ throw new Error("Cannot get object item value by empty string key.");+ }++ if (!property_exists($reference, $key)) {+ throw new Error("Cannot get object item value by non-existent key.");+ }++ return $reference->$key;+ }+}diff --git a/application/Espo/Core/Formula/Functions/VariableSetKeyValueType.php b/application/Espo/Core/Formula/Functions/VariableSetKeyValueType.phpnew file mode 100644index 0000000000..5fe8a0b7a3--- /dev/null+++ b/application/Espo/Core/Formula/Functions/VariableSetKeyValueType.php@@ -0,0 +1,93 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2025 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Core\Formula\Functions;++use Espo\Core\Formula\ArgumentList;+use Espo\Core\Formula\Exceptions\Error;+use stdClass;++/**+ * @noinspection PhpUnused+ */+class VariableSetKeyValueType extends BaseFunction+{+ public function process(ArgumentList $args)+ {+ if (count($args) < 3) {+ $this->throwTooFewArguments();+ }++ $name = $this->evaluate($args[0]);+ $key = $this->evaluate($args[1]);+ $value = $this->evaluate($args[2]);++ if (!is_string($name)) {+ $this->throwBadArgumentValue(1, 'string');+ }++ if (!property_exists($this->getVariables(), $name)) {+ throw new Error("Cannot access by key of non-existing variable.");+ }++ $reference =& $this->getVariables()->$name;++ if (!is_array($reference) && !$reference instanceof stdClass) {+ throw new Error("Cannot access by key of variable that is non-array and non-object.");+ }++ if (is_array($reference)) {+ if (!is_int($key)) {+ throw new Error("Cannot set array item value by non-integer key.");+ }++ if ($key < 0) {+ throw new Error("Cannot set array item value by key that is less than zero.");+ }++ if ($key > count($reference)) {+ throw new Error("Cannot set array item value by key that is greater than length of array.");+ }++ $reference[$key] = $value;++ return;+ }++ if (!is_string($key)) {+ throw new Error("Cannot set object item value by non-string key.");+ }++ if ($key === '') {+ throw new Error("Cannot set object item value by empty string key.");+ }++ $reference->$key = $value;+ }+}diff --git a/application/Espo/Core/Formula/Parser.php b/application/Espo/Core/Formula/Parser.phpindex 4daa4157d6..046fd76d52 100644--- a/application/Espo/Core/Formula/Parser.php+++ b/application/Espo/Core/Formula/Parser.php@@ -106,31 +106,7 @@ class Parser}if ($firstPart[0] == '$') {- $variable = substr($firstPart, 1);-- $isArrayAppend = false;-- if (str_ends_with($firstPart, '[]')) {- $variable = substr($firstPart, 1, -2);-- $isArrayAppend = true;- }-- if ($variable === '' || !preg_match($this->variableNameRegExp, $variable)) {- throw new SyntaxError("Bad variable name `$variable`.");- }-- if ($isArrayAppend) {- return new Node('arrayAppend', [- new Value($variable),- $this->split($secondPart)- ]);- }-- return new Node('assign', [- new Value($variable),- $this->split($secondPart)- ]);+ return $this->applyOperatorVariableAssign($firstPart, $secondPart);}if ($secondPart === '') {@@ -181,6 +157,7 @@ class Parser$isLineComment = false;$parenthesisCounter = 0;$braceCounter = 0;+ $bracketCounter = 0;$modifiedString = $string;@@ -210,7 +187,7 @@ class Parser}if ($isString) {- if (in_array($char, ['(', ')', '{', '}'])) {+ if (in_array($char, ['(', ')', '{', '}', '[', ']'])) {$modifiedString[$i] = '_';} else if (!$isStringStart) {$modifiedString[$i] = ' ';@@ -261,18 +238,23 @@ class Parser$braceCounter++;} else if ($char === '}') {$braceCounter--;+ } else if ($char === '[') {+ $bracketCounter++;+ } else if ($char === ']') {+ $bracketCounter--;}}if ($statementList !== null) {$this->processStringIteration(- $string,- $i,- $statementList,- $parenthesisCounter,- $braceCounter,- $isLineComment,- $isComment+ string: $string,+ i: $i,+ statementList: $statementList,+ parenthesisCounter: $parenthesisCounter,+ braceCounter: $braceCounter,+ bracketCounter: $bracketCounter,+ isLineComment: $isLineComment,+ isComment: $isComment,);}@@ -337,8 +319,9 @@ class Parserarray &$statementList,int $parenthesisCounter,int $braceCounter,+ int $bracketCounter,bool $isLineComment,- bool $isComment+ bool $isComment,): void {$char = $string[$i];@@ -353,7 +336,8 @@ class Parser) {if ($parenthesisCounter === 0 &&- $braceCounter === 0+ $braceCounter === 0 &&+ $bracketCounter === 0) {if ($char === ';') {$lastStatement->setEnd($i, true);@@ -374,11 +358,11 @@ class Parser!$lastStatement->isReady()) {$toContinue = $this->processStringIfStatement(- $string,- $i,- $parenthesisCounter,- $braceCounter,- $lastStatement+ string: $string,+ i: $i,+ parenthesisCounter: $parenthesisCounter,+ braceCounter: $braceCounter,+ statement: $lastStatement,);if ($toContinue) {@@ -422,7 +406,8 @@ class Parser$parenthesisCounter === 0 ||$parenthesisCounter === 1 && $char === '(') &&- $braceCounter === 0+ $braceCounter === 0 &&+ $bracketCounter === 0) {if ($isLineComment || $isComment) {return;@@ -801,9 +786,10 @@ class Parser$parenthesisCounter = 0;$braceCounter = 0;+ $bracketCounter = 0;$hasExcessParenthesis = true;$modifiedExpression = '';- $expressionOutOfParenthesisList = [];+ $topLevelExpressionList = [];$statementList = [];@@ -826,13 +812,17 @@ class Parser$braceCounter++;} else if ($value === '}') {$braceCounter--;+ } else if ($value === '[') {+ $bracketCounter++;+ } else if ($value === ']') {+ $bracketCounter--;}if ($parenthesisCounter === 0 && $i < $expressionLength - 1) {$hasExcessParenthesis = false;}- $expressionOutOfParenthesisList[] = $parenthesisCounter === 0;+ $topLevelExpressionList[] = $parenthesisCounter === 0 && $bracketCounter === 0;}if ($parenthesisCounter !== 0) {@@ -849,6 +839,13 @@ class Parser);}+ if ($bracketCounter !== 0) {+ throw SyntaxError::create(+ 'Incorrect bracket usage in expression ' . $expression . '.',+ 'Incorrect brackets.'+ );+ }+if (strlen($expression) > 1 &&$expression[0] === '(' &&@@ -883,7 +880,7 @@ class Parser}if (- $expressionOutOfParenthesisList[$index] &&+ $topLevelExpressionList[$index] &&!$this->isAtAnotherOperator($index, $operator, $modifiedExpression)) {break;@@ -985,40 +982,7 @@ class Parser}if ($expression[0] === "$") {- $value = substr($expression, 1);-- $isIncrement = false;- $isDecrement = false;-- if (str_ends_with($expression, '++')) {- $isIncrement = true;-- $value = rtrim(substr($value, 0, -2));- }-- if (str_ends_with($expression, '--')) {- $isDecrement = true;-- $value = rtrim(substr($value, 0, -2));- }-- if ($value === '' || !preg_match($this->variableNameRegExp, $value)) {- throw new SyntaxError("Bad variable name `$value`.");- }-- if ($isIncrement) {- return new Node('variableIncrement', [- new Value($value),- ]);- }-- if ($isDecrement) {- return new Node('variableDecrement', [- new Value($value),- ]);- }-- return new Variable($value);+ return $this->splitVariable($expression);}if (is_numeric($expression)) {@@ -1387,4 +1351,118 @@ class Parserreturn $result;}++ /**+ * @throws SyntaxError+ */+ private function applyOperatorVariableAssign(string $firstPart, string $secondPart): Node+ {+ $variable = substr($firstPart, 1);++ $isArrayAppend = false;+ $isKeyValue = false;+ $keyExpression = '';++ if (str_ends_with($firstPart, '[]')) {+ $variable = substr($firstPart, 1, -2);++ $isArrayAppend = true;+ } else if (str_ends_with($firstPart, ']') && str_contains($firstPart, '[')) {+ $bracketPosition = strpos($firstPart, '[');++ $variable = substr($firstPart, 1, $bracketPosition - 1);+ $keyExpression = trim(substr($firstPart, $bracketPosition + 1, -1));++ $isKeyValue = true;++ if ($keyExpression === '') {+ throw new SyntaxError("No expression inside brackets.");+ }+ }++ if ($variable === '' || !preg_match($this->variableNameRegExp, $variable)) {+ throw new SyntaxError("Bad variable name `$variable`.");+ }++ if ($isArrayAppend) {+ return new Node('arrayAppend', [+ new Value($variable),+ $this->split($secondPart)+ ]);+ }++ if ($isKeyValue) {+ return new Node('variableSetKeyValue', [+ new Value($variable),+ $this->split($keyExpression),+ $this->split($secondPart)+ ]);+ }++ return new Node('assign', [+ new Value($variable),+ $this->split($secondPart)+ ]);+ }++ /**+ * @throws SyntaxError+ */+ private function splitVariable(string $expression): Node|Variable+ {+ $value = substr($expression, 1);++ $isIncrement = false;+ $isDecrement = false;+ $isKeyValue = false;+ $keyExpression = '';++ if (str_ends_with($expression, '++')) {+ $isIncrement = true;++ $value = rtrim(substr($value, 0, -2));+ }++ if (str_ends_with($expression, '--')) {+ $isDecrement = true;++ $value = rtrim(substr($value, 0, -2));+ } else if (str_ends_with($expression, ']') && str_contains($expression, '[')) {+ $bracketPosition = strpos($expression, '[');++ $value = substr($expression, 1, $bracketPosition - 1);+ $keyExpression = trim(substr($expression, $bracketPosition + 1, -1));++ $isKeyValue = true;++ if ($keyExpression === '') {+ throw new SyntaxError("No expression inside brackets.");+ }+ }++ if ($value === '' || !preg_match($this->variableNameRegExp, $value)) {+ throw new SyntaxError("Bad variable name `$value`.");+ }++ if ($isIncrement) {+ return new Node('variableIncrement', [+ new Value($value),+ ]);+ }++ if ($isDecrement) {+ return new Node('variableDecrement', [+ new Value($value),+ ]);+ }++ if ($isKeyValue) {+ return new Node('variableGetValueByKey', [+ new Value($value),+ $this->split($keyExpression),+ ]);+ }++ return new Variable($value);+ }}diff --git a/tests/unit/Espo/Core/Formula/EvaluatorTest.php b/tests/unit/Espo/Core/Formula/EvaluatorTest.phpindex 0b5bdf3114..7674e905cc 100644--- a/tests/unit/Espo/Core/Formula/EvaluatorTest.php+++ b/tests/unit/Espo/Core/Formula/EvaluatorTest.php@@ -1841,4 +1841,152 @@ class EvaluatorTest extends TestCase/** @noinspection PhpUnhandledExceptionInspection */$this->evaluator->process($expression);}++ public function testArrayGetSetByKey(): void+ {+ $expression = "+ \$v = list('a', 'b');+ \$v[0] = 'a1';+ \$v[0 + 1] = 'b1';+ \$v[0 + 1];+ ";++ /** @noinspection PhpUnhandledExceptionInspection */+ $result = $this->evaluator->process($expression);++ $this->assertEquals('b1', $result);+ }++ public function testArrayGetByKeyError1(): void+ {+ $expression = "+ \$v = list('a', 'b');+ \$v[0 + 2];+ ";++ $this->expectException(Error::class);++ /** @noinspection PhpUnhandledExceptionInspection */+ $this->evaluator->process($expression);+ }++ public function testArrayGetByKeyError2(): void+ {+ $expression = "+ \$v = list('a', 'b');+ \$v[-1];+ ";++ $this->expectException(Error::class);++ /** @noinspection PhpUnhandledExceptionInspection */+ $this->evaluator->process($expression);+ }++ public function testArrayGetByKeyError3(): void+ {+ $expression = "+ \$v = list('a', 'b');+ \$v['0'];+ ";++ $this->expectException(Error::class);++ /** @noinspection PhpUnhandledExceptionInspection */+ $this->evaluator->process($expression);+ }++ public function testArraySetByKeyError1(): void+ {+ $expression = "+ \$v = list('a', 'b');+ \$v[0 + 3] = 'c';+ ";++ $this->expectException(Error::class);++ /** @noinspection PhpUnhandledExceptionInspection */+ $this->evaluator->process($expression);+ }++ public function testArraySetByKeyError2(): void+ {+ $expression = "+ \$v = list('a', 'b');+ \$v[-1] = 'c';+ ";++ $this->expectException(Error::class);++ /** @noinspection PhpUnhandledExceptionInspection */+ $this->evaluator->process($expression);+ }++ public function testArraySetByKeyError3(): void+ {+ $expression = "+ \$v = list('a', 'b');+ \$v['0'] = 'c';+ ";++ $this->expectException(Error::class);++ /** @noinspection PhpUnhandledExceptionInspection */+ $this->evaluator->process($expression);+ }++ public function testObjectGetSetByKey(): void+ {+ $expression = "+ \$o = object\\create();+ \$o['a'] = 'v';+ \$o['a'];+ ";++ /** @noinspection PhpUnhandledExceptionInspection */+ $result = $this->evaluator->process($expression);++ $this->assertEquals('v', $result);+ }++ public function testObjecSetByKeyError1(): void+ {+ $expression = "+ \$o = object\\create();+ \$o[1] = 'v';+ ";++ $this->expectException(Error::class);++ /** @noinspection PhpUnhandledExceptionInspection */+ $this->evaluator->process($expression);+ }++ public function testObjectSetByKeyError2(): void+ {+ $expression = "+ \$o = object\\create();+ \$o[''] = 'v';+ ";++ $this->expectException(Error::class);++ /** @noinspection PhpUnhandledExceptionInspection */+ $this->evaluator->process($expression);+ }+++ public function testObjectGetByKeyError1(): void+ {+ $expression = "+ \$o = object\\create();+ \$o['a'] = 'v';+ \$o['b'];+ ";++ $this->expectException(Error::class);++ /** @noinspection PhpUnhandledExceptionInspection */+ $this->evaluator->process($expression);+ }}