1
0
mirror of https://github.com/danog/psalm.git synced 2025-01-10 23:18:40 +01:00
psalm/src/Psalm/Internal/Analyzer/Statements/Expression/BinaryOp/CoalesceAnalyzer.php

67 lines
2.0 KiB
PHP
Raw Normal View History

2020-05-19 00:57:02 +02:00
<?php
namespace Psalm\Internal\Analyzer\Statements\Expression\BinaryOp;
use PhpParser;
use Psalm\Internal\Analyzer\Statements\ExpressionAnalyzer;
use Psalm\Internal\Analyzer\StatementsAnalyzer;
use Psalm\Context;
use Psalm\Type;
2020-11-26 03:36:37 +01:00
use function substr;
2020-05-19 00:57:02 +02:00
/**
* @internal
*/
class CoalesceAnalyzer
{
public static function analyze(
StatementsAnalyzer $statements_analyzer,
PhpParser\Node\Expr\BinaryOp\Coalesce $stmt,
2020-05-19 00:57:02 +02:00
Context $context
) : bool {
$left_expr = $stmt->left;
2020-05-19 00:57:02 +02:00
if ($left_expr instanceof PhpParser\Node\Expr\FuncCall
|| $left_expr instanceof PhpParser\Node\Expr\MethodCall
|| $left_expr instanceof PhpParser\Node\Expr\StaticCall
|| $left_expr instanceof PhpParser\Node\Expr\Cast
) {
$left_var_id = '$<tmp coalesce var>' . (int) $left_expr->getAttribute('startFilePos');
2020-05-19 00:57:02 +02:00
ExpressionAnalyzer::analyze($statements_analyzer, $left_expr, clone $context);
2020-05-19 00:57:02 +02:00
$condition_type = $statements_analyzer->node_data->getType($left_expr) ?: Type::getMixed();
2020-05-19 00:57:02 +02:00
$context->vars_in_scope[$left_var_id] = $condition_type;
2020-05-19 00:57:02 +02:00
$left_expr = new PhpParser\Node\Expr\Variable(
substr($left_var_id, 1),
$left_expr->getAttributes()
2020-05-19 00:57:02 +02:00
);
}
$ternary = new PhpParser\Node\Expr\Ternary(
new PhpParser\Node\Expr\Isset_(
[$left_expr],
$stmt->left->getAttributes()
),
$left_expr,
$stmt->right,
$stmt->getAttributes()
2020-05-19 00:57:02 +02:00
);
$old_node_data = $statements_analyzer->node_data;
2020-05-19 00:57:02 +02:00
$statements_analyzer->node_data = clone $statements_analyzer->node_data;
ExpressionAnalyzer::analyze($statements_analyzer, $ternary, clone $context);
2020-05-19 00:57:02 +02:00
$ternary_type = $statements_analyzer->node_data->getType($ternary) ?: Type::getMixed();
2020-05-19 00:57:02 +02:00
$statements_analyzer->node_data = $old_node_data;
2020-05-19 00:57:02 +02:00
$statements_analyzer->node_data->setType($stmt, $ternary_type);
2020-05-19 00:57:02 +02:00
return true;
}
}