[ExpressionLanguage] make a proposal in SyntaxError message
This commit is contained in:
parent
22c00283bb
commit
f19cf8a916
@ -195,13 +195,13 @@ class Parser
|
||||
default:
|
||||
if ('(' === $this->stream->current->value) {
|
||||
if (false === isset($this->functions[$token->value])) {
|
||||
throw new SyntaxError(sprintf('The function "%s" does not exist', $token->value), $token->cursor, $this->stream->getExpression());
|
||||
throw new SyntaxError(sprintf('The function "%s" does not exist', $token->value), $token->cursor, $this->stream->getExpression(), $token->value, array_keys($this->functions));
|
||||
}
|
||||
|
||||
$node = new Node\FunctionNode($token->value, $this->parseArguments());
|
||||
} else {
|
||||
if (!in_array($token->value, $this->names, true)) {
|
||||
throw new SyntaxError(sprintf('Variable "%s" is not valid', $token->value), $token->cursor, $this->stream->getExpression());
|
||||
throw new SyntaxError(sprintf('Variable "%s" is not valid', $token->value), $token->cursor, $this->stream->getExpression(), $token->value, $this->names);
|
||||
}
|
||||
|
||||
// is the name used in the compiled code different
|
||||
|
@ -13,7 +13,7 @@ namespace Symfony\Component\ExpressionLanguage;
|
||||
|
||||
class SyntaxError extends \LogicException
|
||||
{
|
||||
public function __construct($message, $cursor = 0, $expression = '')
|
||||
public function __construct($message, $cursor = 0, $expression = '', $subject = null, array $proposals = null)
|
||||
{
|
||||
$message = sprintf('%s around position %d', $message, $cursor);
|
||||
if ($expression) {
|
||||
@ -21,6 +21,21 @@ class SyntaxError extends \LogicException
|
||||
}
|
||||
$message .= '.';
|
||||
|
||||
if (null !== $subject && null !== $proposals) {
|
||||
$minScore = INF;
|
||||
foreach ($proposals as $proposal) {
|
||||
$distance = levenshtein($subject, $proposal);
|
||||
if ($distance < $minScore) {
|
||||
$guess = $proposal;
|
||||
$minScore = $distance;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($guess) && $minScore < 3) {
|
||||
$message .= sprintf(' Did you mean "%s"?', $guess);
|
||||
}
|
||||
}
|
||||
|
||||
parent::__construct($message);
|
||||
}
|
||||
}
|
||||
|
@ -195,4 +195,16 @@ class ParserTest extends TestCase
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedException \Symfony\Component\ExpressionLanguage\SyntaxError
|
||||
* @expectedExceptionMessage Did you mean "baz"?
|
||||
*/
|
||||
public function testNameProposal()
|
||||
{
|
||||
$lexer = new Lexer();
|
||||
$parser = new Parser(array());
|
||||
|
||||
$parser->parse($lexer->tokenize('foo > bar'), array('foo', 'baz'));
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user