Skip to content

Commit d7d7cbf

Browse files
authored
Improve test coverage and Improve CLI binary file handling (#84)
* Add tests for dynamic class static property transformations and handle edge cases * Refactor return node handling and add tests for variable name inference and malformed docblocks * Add tests for doc comment and native union type extraction in FunctionContractInjector * Refactor class instantiation syntax and improve test coverage for PropertyHookInjector * Refactor IgnoreManager and enhance test coverage with new fixtures and assertions * Enhance test coverage for PathMatcher by adding tests for static source path identification and path inclusion logic * Enhance test coverage for Config by adding tests for project root resolution and configuration handling * Refactor StubManager and enhance test coverage with new tests for resolveStubFiles and loadStubFiles methods * Improve test coverage * Enhance test coverage for TypeFormatter by adding tests for various data types and edge cases * Add new dedicated Validators Test suites tests and remove outdated ValidatorsTest * Add comprehensive tests for GenericValidator and ObjectShapeValidator - Enhanced GenericValidatorTest with additional test cases for validating key-of, value-of, and various array shapes, including support for global constants and enums. - Introduced ObjectShapeValidatorTest to validate object shapes, including handling of required and optional properties, uninitialized properties, and magic getters. - Improved type validation for class-string and int-mask types, ensuring proper error handling for invalid inputs. - Added tests for multi-template and variance scenarios in TypePHPTest to ensure correct handling of generics. * fix code styling * make typep cli binary to type check any file without specifying in the config * Add wildcard include pattern to configuration for broader file matching * Refactor include handling in RunCommand to ensure only valid strings are added * Update README.md to clarify CLI binary type-checking capabilities for standalone scripts
1 parent ecb47b7 commit d7d7cbf

41 files changed

Lines changed: 4184 additions & 952 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.gitignore‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,5 @@ composer.lock
66
index.php
77
benchmark.php
88
.php-cs-fixer.cache
9-
/app
9+
/app
10+
/coverage-report

‎README.md‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
Here is the updated `README.md` reflecting that the CLI binary automatically type-checks any specified script without needing to register it in `typephp.php`:
2+
3+
```markdown
14
<h1 align="center">TypePHP</h1>
25

36
<p align="center">
@@ -76,23 +79,27 @@ Simply run your tests or use your local development server (**Laravel**, **Symfo
7679

7780
## Executing Standalone Scripts (CLI Runner)
7881

79-
For standalone, single-execution PHP scripts that do not have an explicit autoloader entry point, run them directly with the TypePHP CLI binary:
82+
You can run any standalone PHP script directly with the TypePHP CLI binary:
8083

8184
```bash
8285
vendor/bin/typephp script.php
8386
```
8487

88+
Targeting a file directly with the CLI binary automatically type-checks that file—**even if it is not registered in `typephp.php` or falls outside your configured `include` paths**.
89+
90+
Any secondary files required or included by your script will continue to respect your project's configured `include` and `exclude` paths.
91+
8592
---
8693

8794
## Type-Checking Files Anywhere (`"*"` Wildcard Glob)
8895

89-
By default, TypePHP checks standard application folders (`src/**`, `app/**`, `tests/**`). To type-check PHP files anywhere in your project root while still respecting your excluded folders, set the `"*"` wildcard glob in `typephp.php`:
96+
By default, TypePHP checks standard application folders (`src/**`, `app/**`, `tests/**`). To type-check PHP files anywhere in your project root during regular application runs while still respecting your excluded folders, set the `"*"` wildcard glob in `typephp.php`:
9097

9198
```php
9299
// typephp.php
93100
return [
94101
'include' => [
95-
'*', // Intercepts and type-checks PHP files anywhere in the project
102+
'*',
96103
],
97104
'exclude' => [
98105
'vendor/**',
@@ -167,14 +174,14 @@ Define generic templates and TypePHP tracks their state per object instance in m
167174
class Collection
168175
{
169176
/** @param T $item */
170-
public function add(mixed $item): void { /* ... */ }
177+
public function add(mixed $item): void { }
171178
}
172179

173180
// Prebind T = User to this specific instance in WeakMap memory
174181
/** @var Collection<User> $users */
175182
$users = new Collection();
176183

177-
$users->add(new User('Alice')); // Valid
184+
$users->add(new User('Alice'));
178185

179186
$users->add(new Product('SKU-100'));
180187
// Throws TypeError: Argument $item (template T = User) must be of type User, Product given
@@ -207,7 +214,7 @@ class DatabaseService
207214

208215
$service = new DatabaseService();
209216

210-
$service->connect(['driver' => 'pdo_mysql']); // Valid
217+
$service->connect(['driver' => 'pdo_mysql']);
211218

212219
$service->connect(['driver' => 'pdo_invalid']);
213220
// Throws TypeError: Argument $params['driver'] must be a key of DriverManager::DRIVER_MAP

‎phpunit.xml‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
<?xml version="1.0" encoding="UTF-8"?>
2-
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" bootstrap="vendor/autoload.php" colors="true">
2+
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
4+
bootstrap="vendor/autoload.php"
5+
colors="true">
36
<testsuites>
47
<testsuite name="Test Suite">
58
<directory suffix="Test.php">./tests</directory>
@@ -9,5 +12,8 @@
912
<include>
1013
<directory>src</directory>
1114
</include>
15+
<exclude>
16+
<file>src/bootstrap.php</file>
17+
</exclude>
1218
</source>
1319
</phpunit>

‎src/Internal/Ast/ContractVisitor.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ public function enterNode(Node $node): ?array
9999
return null;
100100
}
101101

102-
if ($node instanceof Node\Stmt\Return_ && $node->expr !== null) {
102+
if ($node instanceof Node\Stmt\Return_) {
103103
$this->handleReturn($node);
104104

105105
return null;

‎src/Internal/Ast/FunctionContractInjector.php‎

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -150,23 +150,12 @@ private static function resolveDocComment(Node\Stmt\Function_|Node\Stmt\ClassMet
150150
return $doc;
151151
}
152152

153-
foreach ($node->getComments() as $comment) {
154-
if ($comment instanceof Doc) {
155-
return $comment;
156-
}
157-
}
158-
159153
if ($node->attrGroups !== []) {
160154
foreach ($node->attrGroups as $group) {
161155
$groupDoc = $group->getDocComment();
162156
if ($groupDoc !== null) {
163157
return $groupDoc;
164158
}
165-
foreach ($group->getComments() as $comment) {
166-
if ($comment instanceof Doc) {
167-
return $comment;
168-
}
169-
}
170159
}
171160
}
172161

@@ -286,10 +275,6 @@ private static function resolveThisArg(bool $isClassMethod, Node\Stmt\Function_|
286275

287276
private static function isGenerator(Node\Stmt\Function_|Node\Stmt\ClassMethod $node): bool
288277
{
289-
if ($node->stmts === null) {
290-
return false;
291-
}
292-
293278
$visitor = new class () extends NodeVisitorAbstract {
294279
public bool $isGen = false;
295280

@@ -311,7 +296,9 @@ public function enterNode(Node $n): ?int
311296

312297
$traverser = new NodeTraverser();
313298
$traverser->addVisitor($visitor);
314-
$traverser->traverse($node->stmts);
299+
/** @var array<Node\Stmt> $stmts */
300+
$stmts = $node->stmts;
301+
$traverser->traverse($stmts);
315302

316303
return $visitor->isGen;
317304
}

‎src/Internal/Cli/RunCommand.php‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace TypePHP\Internal\Cli;
66

7+
use TypePHP\Internal\Util\Config;
78
use TypePHP\TypePHP;
89

910
/**
@@ -54,8 +55,29 @@ public function execute(array $args, $outputStream = STDOUT, $errorStream = STDE
5455
}
5556

5657
try {
57-
TypePHP::boot();
5858
$realTarget = realpath($target);
59+
if ($realTarget !== false) {
60+
$normalizedTarget = str_replace('\\', '/', $realTarget);
61+
$currentConfig = Config::get();
62+
$includes = [];
63+
64+
if (\is_array($currentConfig['include'] ?? null)) {
65+
foreach ($currentConfig['include'] as $inc) {
66+
if (\is_string($inc)) {
67+
$includes[] = $inc;
68+
}
69+
}
70+
}
71+
72+
$includes[] = $normalizedTarget;
73+
74+
Config::set([
75+
'include' => array_values(array_unique($includes)),
76+
]);
77+
}
78+
79+
TypePHP::boot();
80+
5981
if ($realTarget !== false) {
6082
require $realTarget;
6183
}

‎src/Internal/Diagnostic/ErrorFactory.php‎

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
namespace TypePHP\Internal\Diagnostic;
66

77
use ReflectionClass;
8-
use Throwable;
98
use TypeError;
109

1110
/**
@@ -168,28 +167,24 @@ private static function mutateException(
168167
?int $targetLine,
169168
array $filteredTrace
170169
): void {
171-
try {
172-
$ref = new ReflectionClass(\Error::class);
170+
$ref = new ReflectionClass(\Error::class);
173171

174-
$propMessage = $ref->getProperty('message');
175-
$propMessage->setValue($e, $message);
172+
$propMessage = $ref->getProperty('message');
173+
$propMessage->setValue($e, $message);
176174

177-
if ($targetFile !== null) {
178-
$propFile = $ref->getProperty('file');
179-
$propFile->setValue($e, $targetFile);
180-
}
175+
if ($targetFile !== null) {
176+
$propFile = $ref->getProperty('file');
177+
$propFile->setValue($e, $targetFile);
178+
}
181179

182-
if ($targetLine !== null) {
183-
$propLine = $ref->getProperty('line');
184-
$propLine->setValue($e, $targetLine);
185-
}
180+
if ($targetLine !== null) {
181+
$propLine = $ref->getProperty('line');
182+
$propLine->setValue($e, $targetLine);
183+
}
186184

187-
if (\count($filteredTrace) > 0) {
188-
$propTrace = $ref->getProperty('trace');
189-
$propTrace->setValue($e, $filteredTrace);
190-
}
191-
} catch (Throwable $err) {
192-
// Silently fallback if reflection mutation fails
185+
if (\count($filteredTrace) > 0) {
186+
$propTrace = $ref->getProperty('trace');
187+
$propTrace->setValue($e, $filteredTrace);
193188
}
194189
}
195190
}

‎src/Internal/Diagnostic/TypeFormatter.php‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,7 @@ public static function formatGivenValue(mixed $value, bool $isSensitive = false)
6868
return "associative array (key '$firstStringKey')";
6969
}
7070

71-
if ($firstNonSequentialIndex !== null) {
72-
return "non-sequential array (index $firstNonSequentialIndex)";
73-
}
74-
75-
return 'array (' . \count($value) . ' items)';
71+
return "non-sequential array (index $firstNonSequentialIndex)";
7672
}
7773

7874
if (\is_bool($value)) {

‎src/Internal/Util/Config.php‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -284,14 +284,14 @@ public static function getArrayValidationStrategy(): string
284284
* Locates the project root directory by searching upwards for vendor/autoload.php or composer.json.
285285
* Caches the result in memory so the search happens exactly once.
286286
*/
287-
public static function getProjectRoot(): string
287+
public static function getProjectRoot(?string $startingDir = null): string
288288
{
289-
if (self::$projectRoot !== null) {
289+
if ($startingDir === null && self::$projectRoot !== null) {
290290
return self::$projectRoot;
291291
}
292292

293293
$cwd = getcwd();
294-
if ($cwd !== false) {
294+
if ($startingDir === null && $cwd !== false) {
295295
$realCwd = realpath($cwd) !== false ? realpath($cwd) : $cwd;
296296
$normCwd = rtrim(str_replace('\\', '/', (string) $realCwd), '/');
297297
if (
@@ -302,7 +302,7 @@ public static function getProjectRoot(): string
302302
}
303303
}
304304

305-
$dir = str_replace('\\', '/', __DIR__);
305+
$dir = str_replace('\\', '/', $startingDir ?? __DIR__);
306306

307307
if (str_contains($dir, '/vendor/')) {
308308
$vendorPos = strrpos($dir, '/vendor/');

‎src/Internal/Util/IgnoreManager.php‎

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

77
use ReflectionClass;
88
use ReflectionFunction;
9-
use Throwable;
109

1110
/**
1211
* @internal High-performance manager for resolving file-level and caller-level @typephp-ignore tags.
@@ -112,7 +111,7 @@ public static function isCallerIgnored(?string $callerClass = null, ?string $cal
112111
continue;
113112
}
114113

115-
if (str_starts_with($function, '__pest_')) {
114+
if (str_contains($function, '__pest_')) {
116115
continue;
117116
}
118117

@@ -198,25 +197,17 @@ private static function checkMethodIgnored(string $class, string $method): bool
198197
return false;
199198
}
200199

201-
try {
202-
/** @var class-string<object> $class */
203-
$refClass = new ReflectionClass($class);
200+
/** @var class-string<object> $class */
201+
$refClass = new ReflectionClass($class);
204202

205-
if ($refClass->hasMethod($method)) {
206-
$refMethod = $refClass->getMethod($method);
207-
if (self::hasIgnoreDocTag($refMethod->getDocComment())) {
208-
return true;
209-
}
210-
}
211-
212-
if (self::hasIgnoreDocTag($refClass->getDocComment())) {
203+
if ($refClass->hasMethod($method)) {
204+
$refMethod = $refClass->getMethod($method);
205+
if (self::hasIgnoreDocTag($refMethod->getDocComment())) {
213206
return true;
214207
}
215-
} catch (Throwable $e) {
216-
return false;
217208
}
218209

219-
return false;
210+
return self::hasIgnoreDocTag($refClass->getDocComment());
220211
}
221212

222213
private static function checkFunctionIgnored(string $function): bool
@@ -232,15 +223,8 @@ private static function checkFunctionIgnored(string $function): bool
232223
return false;
233224
}
234225

235-
try {
236-
$refFunc = new ReflectionFunction($function);
237-
if (self::hasIgnoreDocTag($refFunc->getDocComment())) {
238-
return true;
239-
}
240-
} catch (Throwable $e) {
241-
return false;
242-
}
226+
$refFunc = new ReflectionFunction($function);
243227

244-
return false;
228+
return self::hasIgnoreDocTag($refFunc->getDocComment());
245229
}
246230
}

0 commit comments

Comments
 (0)