Skip to content

Commit 8160f85

Browse files
authored
Fix bug on eager class constructor validation for generic checking ignoring inline var annotation and fix missing support for default property intialiazation, and quality of life improvements (#81)
* Fix bug on generics eager validation of generic type ingoring inline generics var toggle * Add tests for preserving line numbers in multi-line array returns * Enhance ContractVisitor and RuntimeTypeChecker with property validation and error handling improvements; add tests for property default value validation * Refactor LineNumberPreservationTest to improve temporary directory handling and add configuration setup for StreamWrapper * Refactor path validation logic in PathMatcher to improve handling of system variable paths for improve MacOS temp director handling * Add DeepIgnoreTraceDepthTest to validate @typephp-ignore behavior in deep stack traces * Add ignore_trace_depth configuration to control stack trace depth for @typephp-ignore tags * Remove redundant beforeEach reset in DeepIgnoreTraceDepthTest * fix 8.2 ci failing test * fix code styling
1 parent f691f3a commit 8160f85

15 files changed

Lines changed: 700 additions & 80 deletions

‎src/Internal/Ast/ContractVisitor.php‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use PhpParser\Node;
88
use PhpParser\NodeVisitorAbstract;
99
use TypePHP\Internal\Docblock\DocblockExtractor;
10+
use TypePHP\Internal\Util\Config;
1011

1112
/**
1213
* @internal AST Node Visitor that injects contract checks, scope tracking, property hook validation, and parameter/return wrappers into functions and methods.
@@ -71,6 +72,20 @@ public function enterNode(Node $node): ?array
7172
$this->scopeManager->pushScope();
7273
}
7374

75+
if ($node instanceof Node\Expr\Assign || $node instanceof Node\Expr\AssignOp) {
76+
$this->markWriteContext($node->var);
77+
} elseif ($node instanceof Node\Expr\PreInc || $node instanceof Node\Expr\PostInc || $node instanceof Node\Expr\PreDec || $node instanceof Node\Expr\PostDec) {
78+
$this->markWriteContext($node->var);
79+
} elseif ($node instanceof Node\Stmt\Unset_) {
80+
foreach ($node->vars as $v) {
81+
$this->markWriteContext($v);
82+
}
83+
}
84+
85+
if ($node instanceof Node\Stmt\Class_) {
86+
$this->processClassPropertyDefaults($node);
87+
}
88+
7489
if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod) {
7590
$classContext = $this->classStack !== [] ? end($this->classStack) : null;
7691
FunctionContractInjector::inject($node, $classContext);
@@ -135,13 +150,130 @@ public function leaveNode(Node $node): ?Node
135150
}
136151
}
137152

153+
if ($node instanceof Node\Expr\StaticPropertyFetch && $node->name instanceof Node\VarLikeIdentifier) {
154+
$propName = $node->name->toString();
155+
156+
if ($node->getAttribute('typephp_checked') !== true && $node->getAttribute('typephp_write_context') !== true) {
157+
$node->setAttribute('typephp_checked', true);
158+
$classArg = $node->class instanceof Node\Name
159+
? new Node\Expr\ClassConstFetch($node->class, 'class')
160+
: $node->class;
161+
162+
return new Node\Expr\StaticCall(
163+
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker'),
164+
'checkStaticProperty',
165+
[
166+
new Node\Arg($classArg),
167+
new Node\Arg(new Node\Scalar\String_($propName)),
168+
new Node\Arg($node),
169+
new Node\Arg(new Node\Scalar\MagicConst\File()),
170+
new Node\Arg(new Node\Scalar\LNumber($node->getStartLine())),
171+
]
172+
);
173+
}
174+
}
175+
138176
if ($this->isScopeBoundary($node)) {
139177
$this->scopeManager->popScope();
140178
}
141179

142180
return null;
143181
}
144182

183+
private function markWriteContext(Node $node): void
184+
{
185+
$node->setAttribute('typephp_write_context', true);
186+
if ($node instanceof Node\Expr\ArrayDimFetch || $node instanceof Node\Expr\PropertyFetch) {
187+
$this->markWriteContext($node->var);
188+
}
189+
}
190+
191+
private function processClassPropertyDefaults(Node\Stmt\Class_ $node): void
192+
{
193+
if (! Config::isInlinePropertiesEnabled()) {
194+
return;
195+
}
196+
197+
$defaultProps = [];
198+
$hasConstructor = false;
199+
200+
foreach ($node->stmts as $stmt) {
201+
if ($stmt instanceof Node\Stmt\ClassMethod && strtolower($stmt->name->toString()) === '__construct') {
202+
$hasConstructor = true;
203+
} elseif ($stmt instanceof Node\Stmt\Property && ! $stmt->isStatic()) {
204+
$doc = $stmt->getDocComment();
205+
if ($doc !== null && str_contains($doc->getText(), '@var') && ! str_contains($doc->getText(), '@typephp-ignore')) {
206+
foreach ($stmt->props as $p) {
207+
$isExplicitNull = $p->default instanceof Node\Expr\ConstFetch && strtolower($p->default->name->toString()) === 'null';
208+
if ($p->default !== null && ! $isExplicitNull) {
209+
$defaultProps[] = [
210+
'name' => $p->name->toString(),
211+
'line' => $p->getStartLine(),
212+
];
213+
}
214+
}
215+
}
216+
}
217+
}
218+
219+
if ($defaultProps === []) {
220+
return;
221+
}
222+
223+
if (! $hasConstructor) {
224+
$ctorStmts = [];
225+
if ($node->extends !== null) {
226+
$ctorStmts[] = new Node\Stmt\If_(
227+
new Node\Expr\FuncCall(new Node\Name('method_exists'), [
228+
new Node\Arg(new Node\Expr\ClassConstFetch(new Node\Name('parent'), 'class')),
229+
new Node\Arg(new Node\Scalar\String_('__construct')),
230+
]),
231+
['stmts' => [
232+
new Node\Stmt\Expression(new Node\Expr\StaticCall(new Node\Name('parent'), '__construct', [new Node\Arg(new Node\Expr\Variable('_typephp_ctor_args'), false, true)])),
233+
]]
234+
);
235+
}
236+
237+
foreach ($defaultProps as $dp) {
238+
$checkCall = NodeBuilder::createPropertyCheckCall(
239+
new Node\Expr\PropertyFetch(new Node\Expr\Variable('this'), $dp['name']),
240+
new Node\Expr\Variable('this'),
241+
$dp['name']
242+
);
243+
$stmt = new Node\Stmt\Expression(NodeBuilder::createTernaryThrowExpr($checkCall, $dp['line']));
244+
$stmt->setAttribute('typephp_injected', true);
245+
$ctorStmts[] = $stmt;
246+
}
247+
248+
$ctor = new Node\Stmt\ClassMethod('__construct', [
249+
'flags' => Node\Stmt\Class_::MODIFIER_PUBLIC,
250+
'params' => [new Node\Param(new Node\Expr\Variable('_typephp_ctor_args'), null, null, false, true)],
251+
'stmts' => $ctorStmts,
252+
]);
253+
$ctor->setAttribute('typephp_injected', true);
254+
$node->stmts[] = $ctor;
255+
} else {
256+
foreach ($node->stmts as $stmt) {
257+
if ($stmt instanceof Node\Stmt\ClassMethod && strtolower($stmt->name->toString()) === '__construct') {
258+
$injected = [];
259+
foreach ($defaultProps as $dp) {
260+
$checkCall = NodeBuilder::createPropertyCheckCall(
261+
new Node\Expr\PropertyFetch(new Node\Expr\Variable('this'), $dp['name']),
262+
new Node\Expr\Variable('this'),
263+
$dp['name']
264+
);
265+
$checkStmt = new Node\Stmt\Expression(NodeBuilder::createTernaryThrowExpr($checkCall, $dp['line']));
266+
$checkStmt->setAttribute('typephp_injected', true);
267+
$injected[] = $checkStmt;
268+
}
269+
$stmt->stmts = [...$injected, ...($stmt->stmts ?? [])];
270+
271+
break;
272+
}
273+
}
274+
}
275+
}
276+
145277
private function trackDeclarationEntry(Node $node): void
146278
{
147279
if ($node instanceof Node\Stmt\Namespace_) {

‎src/Internal/Ast/PropertyHookInjector.php‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,7 @@ private static function shouldSkipInjection(Node\Stmt\Property $node): bool
4444
return false;
4545
}
4646

47-
$shouldRespectIgnore = (bool) (Config::get()['respect_ignore_tags'] ?? true);
48-
49-
return $shouldRespectIgnore && (str_contains($doc->getText(), '@typephp-ignore') || str_contains($doc->getText(), '@typephp-disable'));
47+
return Config::isRespectIgnoreTagsEnabled() && (str_contains($doc->getText(), '@typephp-ignore') || str_contains($doc->getText(), '@typephp-disable'));
5048
}
5149

5250
private static function processGetHook(Node\PropertyHook $hook, string $propertyName): void

‎src/Internal/Checker/InlineChecker.php‎

Lines changed: 29 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -130,11 +130,7 @@ public static function checkVariable(
130130
?string $caller = null,
131131
mixed $thisOrClass = null
132132
): mixed {
133-
$rawConfig = Config::get()['inline_vars'] ?? [];
134-
/** @var array<string, bool> $config */
135-
$config = \is_array($rawConfig) ? $rawConfig : [];
136-
137-
if (! self::hasActiveInlineChecks($config)) {
133+
if (! Config::hasActiveInlineChecks()) {
138134
return $value;
139135
}
140136

@@ -150,7 +146,7 @@ public static function checkVariable(
150146
$typeNode = self::resolveCallerContext($typeNode, $caller, $thisOrClass);
151147
}
152148

153-
if (! self::shouldValidateType($typeNode, $config)) {
149+
if (! self::shouldValidateType($typeNode)) {
154150
return $value;
155151
}
156152

@@ -166,8 +162,20 @@ public static function checkVariable(
166162
return CallableWrapper::wrapTypeNode($typeNode, $value, $cbPrefix, $registry);
167163
}
168164

169-
$checkGenerics = (bool) ($config['generics'] ?? true);
170-
if ($typeNode instanceof GenericTypeNode && $checkGenerics && \is_object($value)) {
165+
if ($typeNode instanceof GenericTypeNode) {
166+
$baseName = strtolower($typeNode->type->name);
167+
$isCollection = isset(self::ARRAY_TYPES[$baseName]);
168+
169+
if (! $isCollection) {
170+
if (! Config::isInlineGenericsEnabled() && Config::isInlineObjectsEnabled()) {
171+
$typeNode = $typeNode->type;
172+
} elseif (! Config::isInlineGenericsEnabled() && ! Config::isInlineObjectsEnabled()) {
173+
return $value;
174+
}
175+
}
176+
}
177+
178+
if ($typeNode instanceof GenericTypeNode && Config::isInlineGenericsEnabled() && \is_object($value)) {
171179
$err = TemplateManager::bindInstanceFromNode($value, $typeNode, $context);
172180
if ($err !== null) {
173181
return $err;
@@ -225,11 +233,7 @@ public static function checkProperty(mixed $value, mixed $objectOrClass, string
225233
return $value;
226234
}
227235

228-
$rawConfig = Config::get()['inline_vars'] ?? [];
229-
/** @var array<string, bool> $config */
230-
$config = \is_array($rawConfig) ? $rawConfig : [];
231-
232-
if (! ($config['properties'] ?? true)) {
236+
if (! Config::isInlinePropertiesEnabled()) {
233237
return $value;
234238
}
235239

@@ -240,7 +244,7 @@ public static function checkProperty(mixed $value, mixed $objectOrClass, string
240244
return $value;
241245
}
242246

243-
if (! self::shouldValidateType($typeNode, $config)) {
247+
if (! self::shouldValidateType($typeNode)) {
244248
return $value;
245249
}
246250

@@ -260,20 +264,6 @@ public static function checkProperty(mixed $value, mixed $objectOrClass, string
260264
return $value;
261265
}
262266

263-
/**
264-
* Checks if at least one inline variable category is active.
265-
*
266-
* @param array<string, bool> $config
267-
*/
268-
private static function hasActiveInlineChecks(array $config): bool
269-
{
270-
return (bool) ($config['generics'] ?? true)
271-
|| (bool) ($config['callables'] ?? true)
272-
|| (bool) ($config['scalars'] ?? false)
273-
|| (bool) ($config['arrays'] ?? false)
274-
|| (bool) ($config['objects'] ?? false);
275-
}
276-
277267
/**
278268
* Resolves caller class or function context and applies templates & type aliases to the AST.
279269
*/
@@ -550,15 +540,12 @@ private static function getTypeParserComponents(): array
550540
return [$typeParser, $lexer];
551541
}
552542

553-
/**
554-
* @param array<string, bool> $config
555-
*/
556-
private static function shouldValidateType(TypeNode $node, array $config): bool
543+
private static function shouldValidateType(TypeNode $node): bool
557544
{
558-
$checkArrays = (bool) ($config['arrays'] ?? false);
545+
$checkArrays = Config::isInlineArraysEnabled();
559546

560547
if ($node instanceof CallableTypeNode) {
561-
return (bool) ($config['callables'] ?? true);
548+
return Config::isInlineCallablesEnabled();
562549
}
563550

564551
if ($node instanceof ObjectShapeNode || $node instanceof ArrayShapeNode || $node instanceof ArrayTypeNode) {
@@ -573,18 +560,18 @@ private static function shouldValidateType(TypeNode $node, array $config): bool
573560
}
574561

575562
if ($lower === 'callable') {
576-
return (bool) ($config['callables'] ?? true);
563+
return Config::isInlineCallablesEnabled();
577564
}
578565

579566
if (isset(self::ARRAY_TYPES[$lower])) {
580567
return $checkArrays;
581568
}
582569

583570
if (isset(self::SCALAR_TYPES[$lower])) {
584-
return (bool) ($config['scalars'] ?? false);
571+
return Config::isInlineScalarsEnabled();
585572
}
586573

587-
return (bool) ($config['objects'] ?? false);
574+
return Config::isInlineObjectsEnabled();
588575
}
589576

590577
if ($node instanceof GenericTypeNode) {
@@ -593,27 +580,27 @@ private static function shouldValidateType(TypeNode $node, array $config): bool
593580
return $checkArrays;
594581
}
595582

596-
if ((bool) ($config['generics'] ?? true)) {
583+
if (Config::isInlineGenericsEnabled()) {
597584
return true;
598585
}
599586

600-
return (bool) ($config['objects'] ?? false);
587+
return Config::isInlineObjectsEnabled();
601588
}
602589

603590
if ($node instanceof NullableTypeNode) {
604-
return self::shouldValidateType($node->type, $config);
591+
return self::shouldValidateType($node->type);
605592
}
606593

607594
if ($node instanceof UnionTypeNode || $node instanceof IntersectionTypeNode) {
608595
foreach ($node->types as $t) {
609-
if (self::shouldValidateType($t, $config)) {
596+
if (self::shouldValidateType($t)) {
610597
return true;
611598
}
612599
}
613600

614601
return false;
615602
}
616603

617-
return (bool) ($config['scalars'] ?? false);
604+
return Config::isInlineScalarsEnabled();
618605
}
619606
}

‎src/Internal/Cli/ConfigInitCommand.php‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,17 @@ private static function getTemplate(): string
113113
*/
114114
'respect_ignore_tags' => true,
115115
116+
/*
117+
|--------------------------------------------------------------------------
118+
| Ignore Tag Stack Trace Depth
119+
|--------------------------------------------------------------------------
120+
| Controls how many stack frames above a failing type check TypePHP will
121+
| inspect to find an enclosing @typephp-ignore or @typephp-disable tag.
122+
| Default is 25 frames. Increase this if your application or test suite
123+
| uses deep call stacks (e.g. pipelines, middlewares, or nested callers).
124+
*/
125+
'ignore_trace_depth' => 25,
126+
116127
/*
117128
|--------------------------------------------------------------------------
118129
| Array Validation Strategy

‎src/Internal/Diagnostic/ErrorFactory.php‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ final class ErrorFactory
2525
'iterator $',
2626
'return iterator',
2727
'generator sent value',
28+
'property ',
2829
];
2930

3031
/**
@@ -47,9 +48,9 @@ public static function createError(string $message): ErrorMessage
4748
* Prepares a TypeError exception before throwing by filtering internal library frames
4849
* and repointing the exception to the actual application caller location.
4950
*/
50-
public static function prepareException(TypeError $e, ?int $line = null): TypeError
51+
public static function prepareException(TypeError $e, ?int $line = null, ?string $file = null): TypeError
5152
{
52-
$targetFile = null;
53+
$targetFile = $file;
5354
$targetLine = $line;
5455

5556
$message = $e->getMessage();

‎src/Internal/Docblock/DocblockParser.php‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
use TypePHP\Internal\Resolver\SpecialTypeResolver;
2929
use TypePHP\Internal\Util\Config;
3030
use TypePHP\Internal\Util\FileFilter;
31+
use TypePHP\Internal\Util\IgnoreManager;
3132
use TypePHP\Internal\Util\StubManager;
3233
use TypePHP\Internal\Validator\TypeValidatorRegistry;
3334

@@ -472,7 +473,7 @@ public static function parseProperty(string $className, string $propertyName): ?
472473
$typeNode = null;
473474
$isMagicProperty = false;
474475

475-
if ($doc === false && (bool) (Config::get()['magic_properties'] ?? true)) {
476+
if ($doc === false && Config::isMagicPropertiesEnabled()) {
476477
$magicResolved = self::findMagicPropertyDoc($refClass, $propertyName);
477478
if ($magicResolved !== null) {
478479
$doc = $magicResolved['doc'];
@@ -764,9 +765,7 @@ private static function extractRawParamName(object $paramNode): string
764765

765766
private static function shouldIgnoreDoc(string $doc): bool
766767
{
767-
$shouldRespectIgnore = (bool) (Config::get()['respect_ignore_tags'] ?? true);
768-
769-
return $shouldRespectIgnore && (str_contains($doc, '@typephp-ignore') || str_contains($doc, '@typephp-disable'));
768+
return Config::isRespectIgnoreTagsEnabled() && IgnoreManager::hasIgnoreDocTag($doc);
770769
}
771770

772771
/**

0 commit comments

Comments
 (0)