Skip to content

Commit 7067669

Browse files
committed
Enhance constant validation by adding checks for class and global constants, including tests for contract compliance and error handling
1 parent ccd00b7 commit 7067669

8 files changed

Lines changed: 565 additions & 50 deletions

File tree

‎src/Internal/Ast/ContractVisitor.php‎

Lines changed: 134 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,23 @@ public function leaveNode(Node $node): Node|array|null
213213
{
214214
$this->trackDeclarationExit($node);
215215

216+
if ($node instanceof Node\Stmt\Class_ && $node->name !== null) {
217+
$className = $this->resolveQualifiedName($node->name);
218+
if ($className !== null) {
219+
$constChecks = $this->collectUnprovenClassConstantChecks($node, $className);
220+
if ($constChecks !== []) {
221+
return [$node, ...$constChecks];
222+
}
223+
}
224+
}
225+
226+
if ($node instanceof Node\Stmt\Const_) {
227+
$globalConstChecks = $this->collectUnprovenGlobalConstantChecks($node);
228+
if ($globalConstChecks !== []) {
229+
return [$node, ...$globalConstChecks];
230+
}
231+
}
232+
216233
if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Expr\Closure) {
217234
array_pop($this->byRefStack);
218235
}
@@ -283,6 +300,122 @@ public function leaveNode(Node $node): Node|array|null
283300
return null;
284301
}
285302

303+
/**
304+
* @return list<Node\Stmt>
305+
*/
306+
private function collectUnprovenClassConstantChecks(Node\Stmt\Class_ $node, string $className): array
307+
{
308+
$injectedStmts = [];
309+
310+
foreach ($node->stmts as $stmt) {
311+
if (! ($stmt instanceof Node\Stmt\ClassConst)) {
312+
continue;
313+
}
314+
315+
$doc = $stmt->getDocComment();
316+
if ($doc === null || ! str_contains($doc->getText(), '@var')) {
317+
continue;
318+
}
319+
320+
if (Config::isRespectIgnoreTagsEnabled() && str_contains($doc->getText(), '@typephp-ignore')) {
321+
continue;
322+
}
323+
324+
$varTag = DocblockExtractor::extractVarTagFromDoc($doc->getText());
325+
if ($varTag === null) {
326+
continue;
327+
}
328+
329+
$typeString = $varTag[0];
330+
331+
try {
332+
[$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents();
333+
$tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($typeString)));
334+
$typeNode = $typeParser->parse($tokens);
335+
336+
foreach ($stmt->consts as $const) {
337+
if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile)) {
338+
continue;
339+
}
340+
341+
$constName = $const->name->toString();
342+
$fullTarget = $className . '::' . $constName;
343+
$classConstFetch = new Node\Expr\ClassConstFetch(new Node\Name\FullyQualified($className), $constName);
344+
345+
$checkCall = NodeBuilder::createConstantCheckCall(
346+
$fullTarget,
347+
$classConstFetch,
348+
$typeString,
349+
$const->getStartLine()
350+
);
351+
352+
$checkStmt = new Node\Stmt\Expression(NodeBuilder::createTernaryThrowExpr($checkCall, $const->getStartLine()));
353+
$checkStmt->setAttribute('typephp_injected', true);
354+
$injectedStmts[] = $checkStmt;
355+
}
356+
} catch (\Throwable) {
357+
}
358+
}
359+
360+
return $injectedStmts;
361+
}
362+
363+
/**
364+
* @return list<Node\Stmt>
365+
*/
366+
private function collectUnprovenGlobalConstantChecks(Node\Stmt\Const_ $node): array
367+
{
368+
$doc = $node->getDocComment();
369+
if ($doc === null || ! str_contains($doc->getText(), '@var')) {
370+
return [];
371+
}
372+
373+
if (Config::isRespectIgnoreTagsEnabled() && str_contains($doc->getText(), '@typephp-ignore')) {
374+
return [];
375+
}
376+
377+
$varTag = DocblockExtractor::extractVarTagFromDoc($doc->getText());
378+
if ($varTag === null) {
379+
return [];
380+
}
381+
382+
$typeString = $varTag[0];
383+
$injectedStmts = [];
384+
385+
try {
386+
[$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents();
387+
$tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($typeString)));
388+
$typeNode = $typeParser->parse($tokens);
389+
390+
foreach ($node->consts as $const) {
391+
if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile)) {
392+
continue;
393+
}
394+
395+
$constName = $const->name->toString();
396+
$qualifiedConstName = $this->currentNamespace !== ''
397+
? $this->currentNamespace . '\\' . $constName
398+
: $constName;
399+
400+
$constFetch = new Node\Expr\ConstFetch(new Node\Name\FullyQualified($qualifiedConstName));
401+
402+
$checkCall = NodeBuilder::createConstantCheckCall(
403+
$qualifiedConstName,
404+
$constFetch,
405+
$typeString,
406+
$const->getStartLine()
407+
);
408+
409+
$checkStmt = new Node\Stmt\Expression(NodeBuilder::createTernaryThrowExpr($checkCall, $const->getStartLine()));
410+
$checkStmt->setAttribute('typephp_injected', true);
411+
$injectedStmts[] = $checkStmt;
412+
}
413+
} catch (\Throwable) {
414+
}
415+
416+
return $injectedStmts;
417+
}
418+
286419
private function createForeachBoundaryCheck(Node\Stmt\Foreach_ $node): ?Node\Stmt\Expression
287420
{
288421
$targetVarExpr = null;
@@ -324,7 +457,7 @@ private function createForeachBoundaryCheck(Node\Stmt\Foreach_ $node): ?Node\Stm
324457

325458
private static function isLoopBodyFreeOfOpaqueMutations(Node\Stmt\Foreach_ $node): bool
326459
{
327-
$visitor = new class () extends NodeVisitorAbstract {
460+
$visitor = new class() extends NodeVisitorAbstract {
328461
public bool $hasOpaqueCalls = false;
329462

330463
public function enterNode(Node $n): ?int

‎src/Internal/Ast/NodeBuilder.php‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,4 +140,22 @@ public static function createPropertyMemberAssignCheckCall(
140140
]
141141
);
142142
}
143+
144+
public static function createConstantCheckCall(
145+
string $constantName,
146+
Node\Expr $valueExpr,
147+
string $typeString,
148+
int $line
149+
): Node\Expr\FuncCall {
150+
return new Node\Expr\FuncCall(
151+
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkConstant'),
152+
[
153+
new Node\Arg(new Node\Scalar\String_($constantName)),
154+
new Node\Arg($valueExpr),
155+
new Node\Arg(new Node\Scalar\String_($typeString)),
156+
new Node\Arg(new Node\Scalar\MagicConst\File()),
157+
new Node\Arg(new Node\Scalar\LNumber($line)),
158+
]
159+
);
160+
}
143161
}

‎src/Internal/Reporting/ViolationCollector.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ public static function reset(): void
5555
/**
5656
* Handles a validation failure according to the configured on_violation mode ('throw', 'warn', 'report').
5757
*
58-
* @param 'parameter'|'return'|'property'|'variable'|'param-out'|'self-out'|'callback'|'yield'|'send' $kind
58+
* @param 'parameter'|'return'|'property'|'variable'|'param-out'|'self-out'|'callback'|'yield'|'send'|'constant' $kind
5959
*/
6060
public static function handle(
6161
ErrorMessage $error,

‎src/Internal/Reporting/ViolationRecord.php‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
final class ViolationRecord implements JsonSerializable
1313
{
1414
/**
15-
* @param 'parameter'|'return'|'property'|'variable'|'param-out'|'self-out'|'callback'|'yield'|'send' $kind
15+
* @param 'parameter'|'return'|'property'|'variable'|'param-out'|'self-out'|'callback'|'yield'|'send'|'constant' $kind
1616
*/
1717
public function __construct(
1818
public readonly string $file,
@@ -26,8 +26,7 @@ public function __construct(
2626
public readonly int $count = 1,
2727
public readonly ?string $caller = null,
2828
public readonly ?string $declaredIn = null
29-
) {
30-
}
29+
) {}
3130

3231
/**
3332
* Computes a deterministic deduplication hash for this violation.

‎src/Internal/RuntimeTypeChecker.php‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
88
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
9+
use PHPStan\PhpDocParser\Parser\TokenIterator;
910
use TypePHP\Internal\Ast\ScopeCleaner;
1011
use TypePHP\Internal\Checker\GeneratorChecker;
1112
use TypePHP\Internal\Checker\InlineChecker;
@@ -16,10 +17,13 @@
1617
use TypePHP\Internal\Checker\SelfOutChecker;
1718
use TypePHP\Internal\Diagnostic\ErrorFactory;
1819
use TypePHP\Internal\Diagnostic\ErrorMessage;
20+
use TypePHP\Internal\Docblock\DocblockExtractor;
21+
use TypePHP\Internal\Docblock\DocblockNormalizer;
1922
use TypePHP\Internal\Docblock\DocblockParser;
2023
use TypePHP\Internal\Generics\TemplateManager;
2124
use TypePHP\Internal\Reporting\ViolationCollector;
2225
use TypePHP\Internal\Resolver\CallerBoundaryResolver;
26+
use TypePHP\Internal\Resolver\SpecialTypeResolver;
2327
use TypePHP\Internal\Util\Config;
2428
use TypePHP\Internal\Util\IgnoreManager;
2529
use TypePHP\Internal\Validator\TypeValidatorRegistry;
@@ -67,6 +71,47 @@ public static function isEnabled(): bool
6771
return Config::isEnabled();
6872
}
6973

74+
/**
75+
* Validates class-level and global constants against declared @var contracts upon declaration/load.
76+
*/
77+
public static function checkConstant(
78+
string $constantName,
79+
mixed $value,
80+
string $typeString,
81+
string $file = '',
82+
?int $line = null
83+
): mixed {
84+
if (! Config::isEnabled()) {
85+
return $value;
86+
}
87+
88+
try {
89+
$normalized = DocblockNormalizer::normalize($typeString);
90+
[$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents();
91+
$tokens = new TokenIterator($lexer->tokenize($normalized));
92+
$typeNode = $typeParser->parse($tokens);
93+
94+
if ($file !== '') {
95+
$typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file);
96+
}
97+
98+
$context = "Constant {$constantName}";
99+
100+
$err = self::getRegistry()->validate($value, $typeNode, $context);
101+
if ($err !== null) {
102+
if (IgnoreManager::isCallerIgnored()) {
103+
return $value;
104+
}
105+
106+
return ViolationCollector::handle($err, 'constant', $value, $file, $line, $constantName);
107+
}
108+
} catch (\Throwable $e) {
109+
// Silently ignore unexpected parsing errors
110+
}
111+
112+
return $value;
113+
}
114+
70115
/**
71116
* Evaluates member/dimension mutation assignments on an object or static property
72117
* ($obj->prop[$key] = $val or Class::$prop[$key] = $val) atomically before writing.

‎tests/Internal/Ast/NodeBuilderTest.php‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,4 +83,20 @@
8383
->and($call->args)->toHaveCount(5)
8484
;
8585
});
86+
87+
test('createConstantCheckCall creates FuncCall node for RuntimeTypeChecker::checkConstant', function () {
88+
$valExpr = new Node\Expr\ClassConstFetch(new Node\Name\FullyQualified('App\Config'), 'Data');
89+
90+
$call = NodeBuilder::createConstantCheckCall('App\Config::Data', $valExpr, 'list<string>', 12);
91+
92+
expect($call)->toBeInstanceOf(Node\Expr\FuncCall::class)
93+
->and($call->name->toString())->toBe('TypePHP\Internal\RuntimeTypeChecker::checkConstant')
94+
->and($call->args)->toHaveCount(5)
95+
->and($call->args[0]->value->value)->toBe('App\Config::Data')
96+
->and($call->args[1]->value)->toBe($valExpr)
97+
->and($call->args[2]->value->value)->toBe('list<string>')
98+
->and($call->args[3]->value)->toBeInstanceOf(Node\Scalar\MagicConst\File::class)
99+
->and($call->args[4]->value->value)->toBe(12)
100+
;
101+
});
86102
});

0 commit comments

Comments
 (0)