Skip to content

Commit 6b2cbe1

Browse files
committed
Enhance constant handling in ViolationCollector and RuntimeTypeChecker to make sure declared_in data is accurate
1 parent b2da679 commit 6b2cbe1

4 files changed

Lines changed: 74 additions & 6 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ All the documentation lives on the **[typephp.dev](https://typephp.dev/)** websi
284284
TypePHP stands on the shoulders of giants. It simply would not exist without two foundational cornerstones of the PHP ecosystem:
285285

286286
* **[PHPStan](https://phpstan.org/) & [`phpstan/phpdoc-parser`](https://github.com/phpstan/phpdoc-parser)** (created by [Ondřej Mirtes](https://github.com/ondrejmirtes) and contributors):
287-
A massive and sincere debt of gratitude is owed to the PHPStan team. Beyond establishing the modern type standard in PHP, `phpstan/phpdoc-parser` is the parsing powerhouse behind TypePHP. It enables TypePHP to tokenize, parse, and evaluate complex type theory and including reified generics (`@template`), conditional types, intersection/union types, DNF, array shapes, and variance—directly at runtime.
287+
A massive and sincere debt of gratitude is owed to the PHPStan team. Beyond establishing the modern type standard in PHP, `phpstan/phpdoc-parser` is the parsing powerhouse behind TypePHP. It enables TypePHP to tokenize, parse, and evaluate complex type theory and including reified generics (`@template`), conditional types, intersection/union types, DNF, array shapes, and variance directly at runtime.
288288
* **[`nikic/php-parser`](https://github.com/nikic/PHP-Parser)** (created by [Nikita Popov](https://github.com/nikic)):
289289
The gold standard for PHP abstract syntax tree (AST) parsing and code manipulation. It powers TypePHP's transparent stream wrapper interception, format-preserving AST transformations, and zero line-drift instrumentation.
290290

‎src/Internal/Reporting/ViolationCollector.php‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -448,7 +448,7 @@ private static function resolveDeclaredIn(
448448
return $genericDecl;
449449
}
450450

451-
if ($kind === 'variable') {
451+
if ($kind === 'variable' || $kind === 'constant') {
452452
return self::normalizeRelativePath($resolvedFile) . ':' . $resolvedLine;
453453
}
454454

@@ -622,7 +622,8 @@ private static function resolveCallSite(?string $explicitFile, ?int $explicitLin
622622
$appFrames = self::collectApplicationFrames();
623623

624624
if ($explicitFile !== null && $explicitFile !== '' && $explicitLine !== null && $explicitLine > 0) {
625-
$callerLabel = self::formatCallerLabel($appFrames, 0);
625+
$callerIndex = (isset($appFrames[0]['caller']) && str_starts_with($appFrames[0]['caller'], 'TypePHP\\Internal\\')) ? 1 : 0;
626+
$callerLabel = self::formatCallerLabel($appFrames, $callerIndex);
626627

627628
return [$explicitFile, $explicitLine, $callerLabel];
628629
}
@@ -663,6 +664,7 @@ private static function collectApplicationFrames(): array
663664
|| str_contains($normalizedFile, 'bin/typephp')
664665
|| str_contains($normalizedFile, 'vendor/phpunit/')
665666
|| str_contains($normalizedFile, 'vendor/pestphp/')
667+
|| str_contains($normalizedFile, 'vendor/composer/')
666668
) {
667669
continue;
668670
}
@@ -729,6 +731,9 @@ private static function extractFunctionFromMessage(string $message): string
729731
if (preg_match('/^Property\s+([a-zA-Z0-9_\\\\]+(?:::\$[a-zA-Z0-9_\x80-\xff]+)?)/', $message, $m) === 1) {
730732
return trim($m[1]);
731733
}
734+
if (preg_match('/^Constant\s+([a-zA-Z0-9_\\\\]+(?:::[a-zA-Z0-9_\x80-\xff]+)?)/', $message, $m) === 1) {
735+
return trim($m[1]);
736+
}
732737
if (preg_match('/^([^:]+):/', $message, $m) === 1) {
733738
return trim($m[1]);
734739
}
@@ -747,6 +752,9 @@ private static function extractTargetFromMessage(string $message, string $kind):
747752
if (preg_match('/(?:Variable)\s+(\$[a-zA-Z0-9_]+)/', $message, $m) === 1) {
748753
return $m[1];
749754
}
755+
if (preg_match('/^Constant\s+(?:[a-zA-Z0-9_\\\\]+::)?([a-zA-Z0-9_\x80-\xff]+)/', $message, $m) === 1) {
756+
return $m[1];
757+
}
750758
if (str_contains($message, 'Return value')) {
751759
return 'return';
752760
}

‎src/Internal/RuntimeTypeChecker.php‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,12 @@ public static function checkConstant(
103103
return $value;
104104
}
105105

106-
return ViolationCollector::handle($err, 'constant', $value, $file, $line, $constantName);
106+
$target = str_contains($constantName, '::')
107+
? explode('::', $constantName, 2)[1]
108+
: $constantName;
109+
$declaredIn = ($file !== '' && $line !== null) ? "{$file}:{$line}" : null;
110+
111+
return ViolationCollector::handle($err, 'constant', $value, $file, $line, $constantName, $target, $declaredIn);
107112
}
108113
} catch (\Throwable $e) {
109114
// Silently ignore unexpected parsing errors
@@ -145,7 +150,9 @@ public static function checkConstantClosureParam(
145150
return $value;
146151
}
147152

148-
return ViolationCollector::handle($err, 'parameter', $value, $file, $line, $caller, '$' . $paramName);
153+
$declaredIn = ($file !== '' && $line !== null) ? "{$file}:{$line}" : null;
154+
155+
return ViolationCollector::handle($err, 'parameter', $value, null, null, $caller, '$' . $paramName, $declaredIn);
149156
}
150157
} catch (\Throwable $e) {
151158
}
@@ -185,7 +192,9 @@ public static function checkConstantClosureReturn(
185192
return $value;
186193
}
187194

188-
return ViolationCollector::handle($err, 'return', $value, $file, $line, $caller, 'return');
195+
$declaredIn = ($file !== '' && $line !== null) ? "{$file}:{$line}" : null;
196+
197+
return ViolationCollector::handle($err, 'return', $value, $file, $line, $caller, 'return', $declaredIn);
189198
}
190199
} catch (\Throwable $e) {
191200
}

‎tests/TypeChecking/Boundaries/ConstantContractsTest.php‎

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

77
use TypePHP\Exception\TypeError;
88
use TypePHP\Internal\Io\StreamWrapper;
9+
use TypePHP\Internal\Util\Config;
10+
use TypePHP\TypePHP;
911

1012
describe('Class & Global Constant Contracts (@var on const)', function () {
1113
describe('1. Class Constant Validation', function () {
@@ -561,4 +563,53 @@ class StaticallyProvenClosureConst
561563
expect($transformed)->not()->toContain('RuntimeTypeChecker::checkReturn');
562564
});
563565
});
566+
567+
describe('5. Constant Violations in Report Mode (on_violation => report)', function () {
568+
test('records accurate target, caller, and declared_in metadata for class and global constants in report mode', function () {
569+
Config::set(['on_violation' => 'report']);
570+
571+
$source = <<<'PHP'
572+
<?php
573+
574+
declare(strict_types=1);
575+
576+
namespace TypePHP\Tests\TypeChecking\Boundaries;
577+
578+
class FixtureReportModeConst
579+
{
580+
/**
581+
* @var list<int>
582+
*/
583+
public const Data = [
584+
1, 2, 3, 'not_an_int',
585+
];
586+
}
587+
PHP;
588+
589+
$tempDir = sys_get_temp_dir() . '/typephp_const_report_' . uniqid();
590+
mkdir($tempDir, 0777, true);
591+
$filePath = $tempDir . '/FixtureReportModeConst.php';
592+
file_put_contents($filePath, $source);
593+
594+
try {
595+
StreamWrapper::register();
596+
require $filePath;
597+
598+
$violations = TypePHP::getViolations();
599+
expect($violations)->toHaveCount(1)
600+
->and($violations[0]->kind)->toBe('constant')
601+
->and($violations[0]->function)->toBe('TypePHP\Tests\TypeChecking\Boundaries\FixtureReportModeConst::Data')
602+
->and($violations[0]->target)->toBe('Data')
603+
->and($violations[0]->line)->toBe(12)
604+
->and($violations[0]->expected)->toBe('int')
605+
->and($violations[0]->given)->toBe("string 'not_an_int'")
606+
->and($violations[0]->declaredIn)->toContain('FixtureReportModeConst.php:12')
607+
->and($violations[0]->caller)->not()->toContain('RuntimeTypeChecker')
608+
;
609+
} finally {
610+
@unlink($filePath);
611+
@rmdir($tempDir);
612+
}
613+
});
614+
});
564615
});

0 commit comments

Comments
 (0)