Skip to content

Commit

Permalink
make stubbed constant types configurable with comment
Browse files Browse the repository at this point in the history
  • Loading branch information
kkmuffme committed Jul 3, 2023
1 parent 27798e6 commit b412632
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/Psalm/Internal/PhpVisitor/Reflector/ExpressionScanner.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
use Psalm\Aliases;
use Psalm\Codebase;
use Psalm\Config;
use Psalm\Exception\DocblockParseException;
use Psalm\Exception\FileIncludeException;
use Psalm\Internal\Analyzer\ClassLikeAnalyzer;
use Psalm\Internal\Analyzer\CommentAnalyzer;
use Psalm\Internal\Analyzer\Statements\Expression\CallAnalyzer;
use Psalm\Internal\Analyzer\Statements\Expression\Fetch\ConstFetchAnalyzer;
use Psalm\Internal\Analyzer\Statements\Expression\IncludeAnalyzer;
Expand Down Expand Up @@ -151,7 +153,29 @@ private static function registerClassMapFunctionCall(
$type_provider,
$second_arg_value,
$aliases,
) ?? Type::getMixed();
);

// allow docblocks to override the declared value to make constants in stubs configurable
$doc_comment = $second_arg_value->getDocComment();
if ($doc_comment) {
try {
$var_comments = CommentAnalyzer::getTypeFromComment($doc_comment, $file_scanner, $aliases);
foreach ($var_comments as $var_comment) {
if ($var_comment->type) {
$const_type = $var_comment->type;
}

// only check the first @var comment
break;
}
} catch (DocblockParseException $e) {
// do nothing
}
}

if ($const_type === null) {
$const_type = Type::getMixed();
}

$config = Config::getInstance();

Expand Down
42 changes: 42 additions & 0 deletions tests/StubTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -693,6 +693,48 @@ public function testConditionalConstantDefined(): void
$this->analyzeFile($file_path, new Context());
}

/**
* @runInSeparateProcess
*/
public function testStubbedConstantVarCommentType(): void
{
$this->project_analyzer = $this->getProjectAnalyzerWithConfig(
TestConfig::loadFromXML(
dirname(__DIR__),
'<?xml version="1.0"?>
<psalm
errorLevel="1"
>
<projectFiles>
<directory name="src" />
</projectFiles>
<stubs>
<file name="tests/fixtures/stubs/constant_var_comment.phpstub" />
</stubs>
</psalm>',
),
);

$file_path = getcwd() . '/src/somefile.php';

$this->addFile(
$file_path,
'<?php
/**
* @param non-empty-string $arg
* @return void
*/
function hello($arg) {
echo $arg;
}
hello(FOO_BAR);',
);

$this->analyzeFile($file_path, new Context());
}

/**
* @runInSeparateProcess
*/
Expand Down
3 changes: 3 additions & 0 deletions tests/fixtures/stubs/constant_var_comment.phpstub
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?php

define('FOO_BAR', /** @var non-empty-string */ 'world');

0 comments on commit b412632

Please sign in to comment.