EspoCRM – Open Source CRM Application
PHP calendarcontactscrmcrm-platformcrm-systemcustomer-portalcustomer-supportcustomizabledocumentsemail-marketingkanbanleadsopen-sourcephpplatformsales-automationsingle-page-applicationsupport
Formula position
Yuriic26a879bcc23
diff --git a/application/Espo/Core/Formula/Argument.php b/application/Espo/Core/Formula/Argument.phpindex e14ecd06e9..d4c74fb049 100644--- a/application/Espo/Core/Formula/Argument.php+++ b/application/Espo/Core/Formula/Argument.php@@ -69,6 +69,20 @@ class Argument implements Evaluatablethrow new Error("Can't get type from scalar.");}+ public function getPosition(): ?int+ {+ if (+ $this->data instanceof Node ||+ $this->data instanceof Value ||+ $this->data instanceof Variable ||+ $this->data instanceof Attribute+ ) {+ return $this->data->getPosition();+ }++ return null;+ }+/*** Get a nested argument list.*diff --git a/application/Espo/Core/Formula/Evaluator.php b/application/Espo/Core/Formula/Evaluator.phpindex 863b998520..acf77f500c 100644--- a/application/Espo/Core/Formula/Evaluator.php+++ b/application/Espo/Core/Formula/Evaluator.php@@ -31,6 +31,7 @@ namespace Espo\Core\Formula;use Espo\Core\Formula\Exceptions\Error;use Espo\Core\Formula\Exceptions\ExecutionException;+use Espo\Core\Formula\Exceptions\GeneralError;use Espo\Core\Formula\Exceptions\SyntaxError;use Espo\Core\Formula\Exceptions\UnsafeFunction;use Espo\Core\Formula\Functions\Base as DeprecatedBaseFunction;@@ -39,6 +40,7 @@ use Espo\Core\Formula\Parser\Ast\Attribute;use Espo\Core\Formula\Parser\Ast\Node;use Espo\Core\Formula\Parser\Ast\Value;use Espo\Core\Formula\Parser\Ast\Variable;+use Espo\Core\Utils\Log;use Espo\ORM\Entity;use Espo\Core\InjectableFactory;@@ -52,6 +54,8 @@ use stdClass;*/class Evaluator{+ private const int ERROR_PART_LENGTH = 50;+private Parser $parser;private AttributeFetcher $attributeFetcher;/** @var array<string, (Node|Value|Attribute|Variable)> */@@ -64,7 +68,8 @@ class Evaluatorpublic function __construct(private InjectableFactory $injectableFactory,private array $functionClassNameMap = [],- private array $unsafeFunctionList = []+ private array $unsafeFunctionList = [],+ private ?Log $log = null,) {$this->attributeFetcher = $injectableFactory->create(AttributeFetcher::class);$this->parser = new Parser();@@ -122,6 +127,14 @@ class Evaluator$result = $processor->process($item);} catch (ExecutionException $e) {throw new LogicException('Unexpected ExecutionException.', 0, $e);+ } catch (GeneralError $e) {+ $this->processLog($e, $expression);++ throw GeneralError::create(+ message: $e->getMessage(),+ position: $e->getPosition(),+ previous: $e,+ );}$this->attributeFetcher->resetRuntimeCache();@@ -160,4 +173,27 @@ class Evaluator$this->checkIsSafe($subData);}}++ private function processLog(GeneralError $exception, string $expression): void+ {+ $position = $exception->getPosition();++ if ($position === null) {+ return;+ }++ $excerpt = substr($expression, $position, self::ERROR_PART_LENGTH);++ $line = substr_count($expression, "\n", 0, $position) + 1;++ $lastNewline = strrpos(substr($expression, 0, $position), "\n");+ $column = $position - ($lastNewline === false ? -1 : $lastNewline);++ $this->log?->info("Failed formula script; line: {line}, column: {column}. Code:\n{excerpt}", [+ 'excerpt' => $excerpt,+ 'line' => $line,+ 'column' => $column,+ 'position' => $position,+ ]);+ }}diff --git a/application/Espo/Core/Formula/Exceptions/Error.php b/application/Espo/Core/Formula/Exceptions/Error.phpindex ba77b5ccf1..3408dc3c0e 100644--- a/application/Espo/Core/Formula/Exceptions/Error.php+++ b/application/Espo/Core/Formula/Exceptions/Error.php@@ -29,7 +29,9 @@namespace Espo\Core\Formula\Exceptions;-class Error extends \Exception+use Exception;++class Error extends Exception{/*** @var intdiff --git a/application/Espo/Core/Formula/Exceptions/GeneralError.php b/application/Espo/Core/Formula/Exceptions/GeneralError.phpnew file mode 100644index 0000000000..3b566d99b5--- /dev/null+++ b/application/Espo/Core/Formula/Exceptions/GeneralError.php@@ -0,0 +1,61 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Exceptions;++use Throwable;++/**+ * @internal+ */+class GeneralError extends Error+{+ private ?int $position = null;++ /**+ * @internal+ */+ public static function create(+ string $message,+ ?int $position = null,+ Throwable $previous = null,+ ): self {++ $object = new self($message, previous: $previous);++ $object->position = $position;++ return $object;+ }++ public function getPosition(): ?int+ {+ return $this->position;+ }+}diff --git a/application/Espo/Core/Formula/Manager.php b/application/Espo/Core/Formula/Manager.phpindex 3fb9f8b915..52b13bebcc 100644--- a/application/Espo/Core/Formula/Manager.php+++ b/application/Espo/Core/Formula/Manager.php@@ -30,6 +30,7 @@namespace Espo\Core\Formula;use Espo\Core\InjectableFactory;+use Espo\Core\Utils\Log;use Espo\Core\Utils\Metadata;use Espo\ORM\Entity;@@ -42,13 +43,21 @@ class Manager{private Evaluator $evaluator;- public function __construct(InjectableFactory $injectableFactory, Metadata $metadata)- {+ public function __construct(+ InjectableFactory $injectableFactory,+ Metadata $metadata,+ Log $log,+ ) {$functionClassNameMap = $metadata->get(['app', 'formula', 'functionClassNameMap'], []);$unsafeFunctionList = $this->getUnsafeFunctionList($metadata);- $this->evaluator = new Evaluator($injectableFactory, $functionClassNameMap, $unsafeFunctionList);+ $this->evaluator = new Evaluator(+ injectableFactory: $injectableFactory,+ functionClassNameMap: $functionClassNameMap,+ unsafeFunctionList: $unsafeFunctionList,+ log: $log+ );}/**diff --git a/application/Espo/Core/Formula/Parser.php b/application/Espo/Core/Formula/Parser.phpindex 103136cafa..a277c279e7 100644--- a/application/Espo/Core/Formula/Parser.php+++ b/application/Espo/Core/Formula/Parser.php@@ -91,21 +91,38 @@ class Parser*/public function parse(string $expression): Node|Attribute|Variable|Value{- return $this->split($expression, true);+ return $this->split($expression, isRoot: true);}/*** @throws SyntaxError*/- private function applyOperator(string $operator, string $firstPart, string $secondPart): Node- {+ private function applyOperator(+ string $operator,+ string $firstPart,+ string $secondPart,+ int $firstPosition,+ int $secondPosition,+ ): Node {++ $firstPosition = self::shiftPositionOnTrim($firstPart, $firstPosition);+ $secondPosition = self::shiftPositionOnTrim($secondPart, $secondPosition);++ $firstPart = trim($firstPart);+ $secondPart = trim($secondPart);+if ($operator === '=') {if (!strlen($firstPart)) {throw new SyntaxError("Bad operator usage.");}- if ($firstPart[0] == '$') {- return $this->applyOperatorVariableAssign($firstPart, $secondPart);+ if ($firstPart[0] === '$') {+ return $this->applyOperatorVariableAssign(+ firstPart: $firstPart,+ secondPart: $secondPart,+ firstPosition: $firstPosition,+ secondPosition: $secondPosition,+ );}if ($secondPart === '') {@@ -113,8 +130,8 @@ class Parser}return new Node('setAttribute', [- new Value($firstPart),- $this->split($secondPart)+ new Value($firstPart, position: $firstPosition),+ $this->split($secondPart, position: $secondPosition)]);}@@ -125,8 +142,8 @@ class Parser}return new Node($functionName, [- $this->split($firstPart),- $this->split($secondPart),+ $this->split($firstPart, position: $firstPosition),+ $this->split($secondPart, position: $secondPosition),]);}@@ -148,6 +165,7 @@ class Parserstring &$modifiedString,?array &$statementList = null,bool $intoOneLine = false,+ int $position = 0,): bool {$isString = false;@@ -254,6 +272,7 @@ class ParserbracketCounter: $bracketCounter,isLineComment: $isLineComment,isComment: $isComment,+ position: $position,);}@@ -309,6 +328,7 @@ class Parserint $bracketCounter,bool $isLineComment,bool $isComment,+ int $position,): void {$char = $string[$i];@@ -373,7 +393,10 @@ class Parser// Not a `while` statement, but likely a `while` function.array_pop($statementList);- $lastStatement = new StatementRef($lastStatement->getStart());+ $lastStatement = new StatementRef(+ start: $lastStatement->getStart(),+ );+$statementList[] = $lastStatement;if ($char === ';') {@@ -424,7 +447,9 @@ class Parser}if ($this->isOnWhile($string, $i)) {- $statementList[] = new WhileRef($i);+ $statementList[] = new WhileRef(+ start: $i,+ );$i += 4;@@ -436,7 +461,9 @@ class Parser$char !== ';' &&$char !== '/') {- $statementList[] = new StatementRef($i);+ $statementList[] = new StatementRef(+ start: $i,+ );}}}@@ -767,8 +794,14 @@ class Parser/*** @throws SyntaxError*/- private function split(string $expression, bool $isRoot = false): Node|Attribute|Variable|Value- {+ private function split(+ string $expression,+ bool $isRoot = false,+ int $position = 0,+ ): Node|Attribute|Variable|Value {++ $position = Parser::shiftPositionOnTrim($expression, $position);+$expression = trim($expression);$parenthesisCounter = 0;@@ -780,7 +813,13 @@ class Parser$statementList = [];- $isStringNotClosed = $this->processString($expression, $modifiedExpression, $statementList, true);+ $isStringNotClosed = $this->processString(+ string: $expression,+ modifiedString: $modifiedExpression,+ statementList: $statementList,+ intoOneLine: true,+ position: $position,+ );if ($isStringNotClosed) {throw SyntaxError::create('String is not closed.');@@ -841,11 +880,20 @@ class Parser) {$expression = substr($expression, 1, strlen($expression) - 2);- return $this->split($expression, true);+ return $this->split(+ expression: $expression,+ isRoot: true,+ position: $position + 1,+ );}if ($statementList !== null && count($statementList)) {- return $this->processStatementList($expression, $statementList, $isRoot);+ return $this->processStatementList(+ expression: $expression,+ statementList: $statementList,+ isRoot: $isRoot,+ position: $position,+ );}$firstOperator = null;@@ -930,34 +978,50 @@ class Parserif ($firstOperator) {/** @var int $minIndex */- $firstPart = substr($expression, 0, $minIndex);- $secondPart = substr($expression, $minIndex + strlen($firstOperator));+ $secondIndex = $minIndex + strlen($firstOperator);- $firstPart = trim($firstPart);- $secondPart = trim($secondPart);-- return $this->applyOperator($firstOperator, $firstPart, $secondPart);+ $firstPart = substr($expression, 0, $minIndex);+ $secondPart = substr($expression, $secondIndex);++ return $this->applyOperator(+ operator: $firstOperator,+ firstPart: $firstPart,+ secondPart: $secondPart,+ firstPosition: $position,+ secondPosition: $position + $secondIndex,+ );}+ $position = self::shiftPositionOnTrim($expression, $position);+$expression = trim($expression);if ($expression[0] === '!') {return new Node('logical\\not', [- $this->split(substr($expression, 1))+ $this->split(+ expression: substr($expression, 1),+ position: $position + 1,+ )]);}if ($expression[0] === '-') {return new Node('numeric\\subtraction', [new Value(0),- $this->split(substr($expression, 1))+ $this->split(+ expression: substr($expression, 1),+ position: $position + 1,+ )]);}if ($expression[0] === '+') {return new Node('numeric\\summation', [new Value(0),- $this->split(substr($expression, 1))+ $this->split(+ expression: substr($expression, 1),+ position: $position + 1,+ )]);}@@ -965,11 +1029,14 @@ class Parser$expression[0] === "'" && $expression[strlen($expression) - 1] === "'" ||$expression[0] === "\"" && $expression[strlen($expression) - 1] === "\"") {- return new Value(self::prepareStringValue($expression));+ return new Value(+ value: self::prepareStringValue($expression),+ position: $position,+ );}if ($expression[0] === "$") {- return $this->splitVariable($expression);+ return $this->splitVariable($expression, position: $position);}if (is_numeric($expression)) {@@ -977,7 +1044,10 @@ class Parser(int) $expression :(float) $expression;- return new Value($value);+ return new Value(+ value: $value,+ position: $position,+ );}if ($expression === 'true') {@@ -1004,22 +1074,33 @@ class Parser$firstOpeningBraceIndex = strpos($expression, '(');if ($firstOpeningBraceIndex > 0) {- $functionName = trim(substr($expression, 0, $firstOpeningBraceIndex));+ $functionNamePart = substr($expression, 0, $firstOpeningBraceIndex);++ $functionPosition = self::shiftPositionOnTrim($functionNamePart, $position);++ $functionName = trim($functionNamePart);+$functionContent = substr($expression, $firstOpeningBraceIndex + 1, -1);- $argumentList = $this->parseArgumentListFromFunctionContent($functionContent);+ $argumentPosition = $position + $firstOpeningBraceIndex + 1;++ $argumentList = $this->parseArgumentListFromFunctionContent($functionContent, $argumentPosition);$argumentSplitList = [];- foreach ($argumentList as $argument) {- $argumentSplitList[] = $this->split($argument);+ foreach ($argumentList as [$argument, $argumentPosition]) {+ $argumentSplitList[] = $this->split($argument, position: $argumentPosition);}if ($functionName === '' || !preg_match($this->functionNameRegExp, $functionName)) {throw new SyntaxError("Bad function name `$functionName`.");}- return new Node($functionName, $argumentSplitList);+ return new Node(+ type: $functionName,+ childNodes: $argumentSplitList,+ position: $functionPosition,+ );}}@@ -1035,7 +1116,10 @@ class Parserthrow SyntaxError::create("Attribute ends with dot.");}- return new Attribute($expression);+ return new Attribute(+ name: $expression,+ position: $position,+ );}private function isAtAnotherOperator(int $index, string $operator, string $expression): bool@@ -1083,6 +1167,7 @@ class Parserstring $expression,array $statementList,bool $isRoot,+ int $position): Node|Value|Attribute|Variable {$parsedPartList = [];@@ -1098,9 +1183,11 @@ class Parserthrow new LogicException();}- $part = self::sliceByStartEnd($expression, $start, $end);+ [$part, $shift] = self::sliceByStartEnd($expression, $start, $end);++ $itemPosition = $position + $start + $shift;- $parsedPart = $this->split($part);+ $parsedPart = $this->split($part, position: $itemPosition);} else if ($statement instanceof IfRef) {if (!$isRoot || !$statement->isReady()) {throw SyntaxError::create(@@ -1125,20 +1212,32 @@ class Parserthrow new LogicException();}- $conditionPart = self::sliceByStartEnd($expression, $conditionStart, $conditionEnd);- $thenPart = self::sliceByStartEnd($expression, $thenStart, $thenEnd);- $elsePart = $elseStart !== null && $elseEnd !== null ?- self::sliceByStartEnd($expression, $elseStart, $elseEnd) : null;+ [$conditionPart, $conditionShift] = self::sliceByStartEnd($expression, $conditionStart, $conditionEnd);++ $conditionPosition = $position + $conditionStart + $conditionShift;++ [$thenPart, $thenShift] = self::sliceByStartEnd($expression, $thenStart, $thenEnd);++ $thenPosition = $position + $thenStart + $thenShift;++ $elsePart = null;+ $elsePosition = null;++ if ($elseStart !== null && $elseEnd) {+ [$elsePart, $elseShift] = self::sliceByStartEnd($expression, $elseStart, $elseEnd);++ $elsePosition = $position + $elseStart + $elseShift;+ }$parsedPart = $statement->getElseKeywordEnd() ?new Node('ifThenElse', [- $this->split($conditionPart),- $this->split($thenPart, true),- $this->split($elsePart ?? '', true)+ $this->split($conditionPart, position: $conditionPosition),+ $this->split($thenPart, true, position: $thenPosition),+ $this->split($elsePart ?? '', true, position: $elsePosition ?? -1)]) :new Node('ifThen', [- $this->split($conditionPart),- $this->split($thenPart, true)+ $this->split($conditionPart, position: $conditionPosition),+ $this->split($thenPart, true, position: $thenPosition)]);} else if ($statement instanceof WhileRef) {if (!$isRoot || !$statement->isReady()) {@@ -1162,12 +1261,17 @@ class Parserthrow new LogicException();}- $conditionPart = self::sliceByStartEnd($expression, $conditionStart, $conditionEnd);- $bodyPart = self::sliceByStartEnd($expression, $bodyStart, $bodyEnd);+ [$conditionPart, $conditionShift] = self::sliceByStartEnd($expression, $conditionStart, $conditionEnd);++ $conditionPosition = $position + $conditionStart + $conditionShift;++ [$bodyPart, $bodyShift] = self::sliceByStartEnd($expression, $bodyStart, $bodyEnd);++ $bodyPosition = $position + $bodyStart + $bodyShift;$parsedPart = new Node('while', [- $this->split($conditionPart),- $this->split($bodyPart, true)+ $this->split($conditionPart, position: $conditionPosition),+ $this->split($bodyPart, true, position: $bodyPosition)]);}@@ -1188,15 +1292,22 @@ class Parserreturn new Node('bundle', $parsedPartList);}- private static function sliceByStartEnd(string $expression, int $start, int $end): string+ /**+ * @return array{string, int}+ */+ private static function sliceByStartEnd(string $expression, int $start, int $end): array{- return trim(substr($expression, $start, $end - $start));+ $part = substr($expression, $start, $end - $start);++ $shift = strlen($part) - strlen(ltrim($part));++ return [trim($part), $shift];}/**- * @return string[]+ * @return array{string, int}[]*/- private function parseArgumentListFromFunctionContent(string $functionContent): array+ private function parseArgumentListFromFunctionContent(string $functionContent, int $position): array{$functionContent = trim($functionContent);@@ -1251,19 +1362,17 @@ class Parser$previousCommaIndex = 0;}- $argument = trim(- substr(- $functionContent,- $previousCommaIndex,- $commaIndexList[$i] - $previousCommaIndex- )- );+ $part = substr($functionContent, $previousCommaIndex, $commaIndexList[$i] - $previousCommaIndex);++ $itemPosition = self::shiftPositionOnTrim($part, $position + $previousCommaIndex);++ $argument = trim($part);if ($argument === '' && $i === count($commaIndexList) - 1) {continue;}- $argumentList[] = $argument;+ $argumentList[] = [$argument, $itemPosition];}return $argumentList;@@ -1336,8 +1445,13 @@ class Parser/*** @throws SyntaxError*/- private function applyOperatorVariableAssign(string $firstPart, string $secondPart): Node- {+ private function applyOperatorVariableAssign(+ string $firstPart,+ string $secondPart,+ int $firstPosition,+ int $secondPosition,+ ): Node {+$variable = substr($firstPart, 1);$isArrayAppend = false;@@ -1354,7 +1468,13 @@ class Parser$variable = substr($firstPart, 1, $bracketPosition - 1);$keyPart = trim(substr($firstPart, $bracketPosition));- $keyPath = array_map(fn ($it) => $this->split($it), $this->splitKeys($keyPart));++ $keyPath = array_map(function ($it) use ($firstPosition) {+ return $this->split(+ expression: $it,+ position: $firstPosition+ );+ }, $this->splitKeys($keyPart));$isKeyValue = true;}@@ -1363,10 +1483,12 @@ class Parserthrow new SyntaxError("Bad variable name `$variable`.");}+ $secondNode = $this->split($secondPart, position: $secondPosition);+if ($isArrayAppend) {return new Node('arrayAppend', [new Value($variable),- $this->split($secondPart)+ $secondNode]);}@@ -1374,20 +1496,20 @@ class Parserreturn new Node('variableSetKeyValue', [new Value($variable),new Node('list', $keyPath),- $this->split($secondPart)+ $secondNode]);}return new Node('assign', [new Value($variable),- $this->split($secondPart)+ $secondNode]);}/*** @throws SyntaxError*/- private function splitVariable(string $expression): Node|Variable+ private function splitVariable(string $expression, int $position): Node|Variable{$value = substr($expression, 1);@@ -1410,7 +1532,10 @@ class Parser$bracketPosition = strpos($expression, '[') ?: 0;$value = substr($expression, 1, $bracketPosition - 1);$keyPart = trim(substr($expression, $bracketPosition));- $keyPath = array_map(fn ($it) => $this->split($it), $this->splitKeys($keyPart));++ $keyPath = array_map(function ($it) use ($position) {+ return $this->split($it, position: $position);+ }, $this->splitKeys($keyPart));$isKeyValue = true;}@@ -1421,24 +1546,27 @@ class Parserif ($isIncrement) {return new Node('variableIncrement', [- new Value($value),+ new Value($value, position: $position),]);}if ($isDecrement) {return new Node('variableDecrement', [- new Value($value),+ new Value($value, position: $position),]);}if ($isKeyValue) {return new Node('variableGetValueByKey', [- new Value($value),- new Node('list', $keyPath),+ new Value($value, position: $position),+ new Node('list', $keyPath, position: $position),]);}- return new Variable($value);+ return new Variable(+ name: $value,+ position: $position,+ );}/**@@ -1449,7 +1577,11 @@ class Parser{$modifiedExpression = '';- $this->processString($expression, $modifiedExpression, $statementList, true);+ $this->processString(+ string: $expression,+ modifiedString: $modifiedExpression,+ intoOneLine: true,+ );$expressionLength = strlen($modifiedExpression);@@ -1511,4 +1643,11 @@ class Parserreturn $output;}++ private static function shiftPositionOnTrim(string $expression, int $position): int+ {+ $position += strlen($expression) - strlen(ltrim($expression));++ return $position;+ }}diff --git a/application/Espo/Core/Formula/Parser/Ast/Attribute.php b/application/Espo/Core/Formula/Parser/Ast/Attribute.phpindex e835f7bac3..ad09beabc0 100644--- a/application/Espo/Core/Formula/Parser/Ast/Attribute.php+++ b/application/Espo/Core/Formula/Parser/Ast/Attribute.php@@ -34,11 +34,18 @@ namespace Espo\Core\Formula\Parser\Ast;*/class Attribute{- public function __construct(private string $name)- {}+ public function __construct(+ private string $name,+ private ?int $position = null,+ ) {}public function getName(): string{return $this->name;}++ public function getPosition(): ?int+ {+ return $this->position;+ }}diff --git a/application/Espo/Core/Formula/Parser/Ast/Node.php b/application/Espo/Core/Formula/Parser/Ast/Node.phpindex 2d63053ef7..ab02de39b8 100644--- a/application/Espo/Core/Formula/Parser/Ast/Node.php+++ b/application/Espo/Core/Formula/Parser/Ast/Node.php@@ -37,8 +37,11 @@ class Node/*** @param (Node|Value|Attribute|Variable)[] $childNodes*/- public function __construct(private string $type, private array $childNodes)- {}+ public function __construct(+ private string $type,+ private array $childNodes,+ private ?int $position = null,+ ) {}public function getType(): string{@@ -52,4 +55,9 @@ class Node{return $this->childNodes;}++ public function getPosition(): ?int+ {+ return $this->position;+ }}diff --git a/application/Espo/Core/Formula/Parser/Ast/Value.php b/application/Espo/Core/Formula/Parser/Ast/Value.phpindex 2b6b922931..3eea14883c 100644--- a/application/Espo/Core/Formula/Parser/Ast/Value.php+++ b/application/Espo/Core/Formula/Parser/Ast/Value.php@@ -34,11 +34,18 @@ namespace Espo\Core\Formula\Parser\Ast;*/class Value{- public function __construct(private mixed $value)- {}+ public function __construct(+ private mixed $value,+ private ?int $position = null,+ ) {}public function getValue(): mixed{return $this->value;}++ public function getPosition(): ?int+ {+ return $this->position;+ }}diff --git a/application/Espo/Core/Formula/Parser/Ast/Variable.php b/application/Espo/Core/Formula/Parser/Ast/Variable.phpindex 0330a2d644..28cbed81bb 100644--- a/application/Espo/Core/Formula/Parser/Ast/Variable.php+++ b/application/Espo/Core/Formula/Parser/Ast/Variable.php@@ -34,11 +34,18 @@ namespace Espo\Core\Formula\Parser\Ast;*/class Variable{- public function __construct(private string $name)- {}+ public function __construct(+ private string $name,+ private ?int $position = null,+ ) {}public function getName(): string{return $this->name;}++ public function getPosition(): ?int+ {+ return $this->position;+ }}diff --git a/application/Espo/Core/Formula/Parser/Statement/IfRef.php b/application/Espo/Core/Formula/Parser/Statement/IfRef.phpindex d39071b6d6..e31d2c647d 100644--- a/application/Espo/Core/Formula/Parser/Statement/IfRef.php+++ b/application/Espo/Core/Formula/Parser/Statement/IfRef.php@@ -51,8 +51,7 @@ class IfRefprivate bool $hasInlineElse = false;private int $state = self::STATE_EMPTY;- public function __construct()- {}+ public function __construct() {}public function setConditionStart(int $conditionStart): void{diff --git a/application/Espo/Core/Formula/Parser/Statement/StatementRef.php b/application/Espo/Core/Formula/Parser/Statement/StatementRef.phpindex 7fe1b7727f..45b2a6d52d 100644--- a/application/Espo/Core/Formula/Parser/Statement/StatementRef.php+++ b/application/Espo/Core/Formula/Parser/Statement/StatementRef.php@@ -33,8 +33,10 @@ class StatementRef{private bool $endedWithSemicolon = false;- public function __construct(private int $start, private ?int $end = null)- {}+ public function __construct(+ private int $start,+ private ?int $end = null,+ ) {}public function setEnd(int $end, bool $endedWithSemicolon = false): void{diff --git a/application/Espo/Core/Formula/Parser/Statement/WhileRef.php b/application/Espo/Core/Formula/Parser/Statement/WhileRef.phpindex e8c6266cd1..652bb400d7 100644--- a/application/Espo/Core/Formula/Parser/Statement/WhileRef.php+++ b/application/Espo/Core/Formula/Parser/Statement/WhileRef.php@@ -43,8 +43,9 @@ class WhileRefprivate ?int $bodyEnd = null;private int $state = self::STATE_EMPTY;- public function __construct(private int $start)- {}+ public function __construct(+ private int $start+ ) {}public function setConditionStart(int $conditionStart): void{diff --git a/application/Espo/Core/Formula/Processor.php b/application/Espo/Core/Formula/Processor.phpindex eec059ebc3..94c9ee6815 100644--- a/application/Espo/Core/Formula/Processor.php+++ b/application/Espo/Core/Formula/Processor.php@@ -33,6 +33,7 @@ use Espo\Core\Formula\Exceptions\BadArgumentType;use Espo\Core\Formula\Exceptions\BadArgumentValue;use Espo\Core\Formula\Exceptions\ExecutionException;use Espo\Core\Formula\Exceptions\FunctionRuntimeError;+use Espo\Core\Formula\Exceptions\GeneralError;use Espo\Core\Formula\Exceptions\TooFewArguments;use Espo\Core\Formula\Exceptions\UndefinedKey;use Espo\Core\Formula\Functions\Base as DeprecatedBaseFunction;@@ -83,6 +84,7 @@ class Processor* @return mixed A result of evaluation. An array if an argument list was passed.* @throws Error* @throws ExecutionException+ * @throws GeneralError*/public function process(Evaluatable $item): mixed{@@ -94,7 +96,15 @@ class Processorthrow new InvalidArgumentException();}- $function = $this->functionFactory->create($item->getType(), $this->entity, $this->variables);+ try {+ $function = $this->functionFactory->create($item->getType(), $this->entity, $this->variables);+ } catch (Exceptions\UnknownFunction $e) {+ throw GeneralError::create(+ message: $e->getMessage(),+ position: $item->getPosition(),+ previous: $e,+ );+ }if ($function instanceof Func || $function instanceof FuncVariablesAware) {return $this->processFunc($item, $function);@@ -109,16 +119,29 @@ class Processor} catch (UndefinedKey $e) {throw UndefinedKey::cloneWithLevelRisen($e);} catch (TooFewArguments|BadArgumentType|BadArgumentValue $e) {- $message = sprintf('Function %s; %s', $item->getType(), $e->getLogMessage());+ $message = $this->prepareMessage($item->getType(), $e->getLogMessage());- throw new Error($message);+ throw GeneralError::create(+ message: $message,+ position: $item->getPosition(),+ previous: $e,+ );} catch (FunctionRuntimeError $e) {- $message = sprintf('Function %s; %s', $item->getType(), $e->getMessage());+ $message = $this->prepareMessage($item->getType(), $e->getMessage());- throw new Error($message);+ throw GeneralError::create(+ message: $message,+ position: $item->getPosition(),+ previous: $e,+ );}}+ private function prepareMessage(string $type, string $message): string+ {+ return sprintf('Function %s; %s', $type, $message);+ }+/*** @throws Error*/@@ -193,13 +216,21 @@ class Processorreturn $function->process($evaluatedArguments);} catch (TooFewArguments|BadArgumentType|BadArgumentValue $e) {- $message = sprintf('Function %s; %s', $item->getType(), $e->getLogMessage());+ $message = $this->prepareMessage($item->getType(), $e->getLogMessage());- throw new Error($message);+ throw GeneralError::create(+ message: $message,+ position: $item->getPosition(),+ previous: $e,+ );} catch (FunctionRuntimeError $e) {- $message = sprintf('Function %s; %s', $item->getType(), $e->getMessage());+ $message = $this->prepareMessage($item->getType(), $e->getMessage());- throw new Error($message);+ throw GeneralError::create(+ message: $message,+ position: $item->getPosition(),+ previous: $e,+ );}}}diff --git a/tests/unit/Espo/Core/Formula/EvaluatorTest.php b/tests/unit/Espo/Core/Formula/EvaluatorTest.phpindex 9da492ad6c..e6d2f08e0b 100644--- a/tests/unit/Espo/Core/Formula/EvaluatorTest.php+++ b/tests/unit/Espo/Core/Formula/EvaluatorTest.php@@ -48,10 +48,9 @@ use tests\unit\ContainerMocker;class EvaluatorTest extends TestCase{- /**- * @var Evaluator- */- private $evaluator;+ private ?Evaluator $evaluator = null;++ private ?Log $log = null;protected function setUp(): void{@@ -81,7 +80,14 @@ class EvaluatorTest extends TestCase$injectableFactory = new InjectableFactory($container, $bindingContainer);- $this->evaluator = new Evaluator($injectableFactory, [], ['test\\unsafe']);+ $this->log = $this->createMock(Log::class);++ $this->evaluator = new Evaluator(+ injectableFactory: $injectableFactory,+ functionClassNameMap: [],+ unsafeFunctionList: ['test\\unsafe'],+ log: $this->log,+ );}protected function tearDown() : void@@ -2176,4 +2182,57 @@ class EvaluatorTest extends TestCase$this->assertEquals([0, 1], $vars->b);$this->assertEquals([0, 1], $vars->c);}++ public function testLoggingBadFunction(): void+ {+ $expression = <<<EOF+ \$a = 1;++ test();+ EOF;++ $this->log->expects(self::once())+ ->method('info')+ ->with(+ $this->anything(),+ [+ 'excerpt' => 'test();',+ 'line' => 3,+ 'column' => 1,+ 'position' => 11,+ ],+ );++ try {+ $this->evaluator->process($expression);+ } catch (Error) {}+ }++ public function testLoggingError(): void+ {+ $expression = <<<EOF+ \$a = 'a';+ if (1) {+ string\contains(\$a);+ \$b = 'b';+ }++ EOF;++ $this->log->expects(self::once())+ ->method('info')+ ->with(+ $this->anything(),+ [+ 'excerpt' => "string\contains(\$a);\r\n \$b = 'b';\r\n}\r\n",+ 'line' => 3,+ 'column' => 5,+ 'position' => 25,+ ],+ );++ try {+ $this->evaluator->process($expression);+ } catch (Error) {}+ }}