Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 89 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,87 @@ TypePHP is a transparent, pure-PHP runtime type checker. You don't have to refac

**[Read the full TypePHP documentation »](https://typephp-php.github.io/docs/)**

**[Quick Start Guide »](https://typephp-php.github.io/docs/getting-started/quick-start)**
---

## Installation

Install TypePHP as a development dependency via Composer:

```bash
composer require typephp/typephp --dev
```

*Note: TypePHP boots automatically via Composer's autoloader. No service providers, bootstrap edits, or framework configurations are required.*

---

## Quick Start

### 1. Initialize Configuration (Optional)

Generate a default `typephp.php` configuration file in your project root:

```bash
vendor/bin/typephp config:init
```

### 2. Write Standard DocBlocks

Annotate your functions, methods, and classes with standard static analysis DocBlocks:

```php
namespace App\Services;

class PaymentService
{
/**
* @param positive-int $amount
* @param array{gateway: 'stripe'|'paypal', currency: non-empty-string} $options
* @return non-empty-string
*/
public function charge(int $amount, array $options): string
{
return "Transaction successful";
}
}
```

### 3. Run Your Application or Tests

If your application runs through an entry point where `require 'vendor/autoload.php'` is declared (such as a web framework's `public/index.php`, CLI commands, or test runners like **Pest** and **PHPUnit**), **TypePHP runs automatically and transparently in the background**.

Simply run your tests or use your local development server (**Laravel**, **Symfony**, **FrankenPHP**, **PHP-FPM**). TypePHP immediately intercepts and enforces all parameter, return, shape, and generic contracts in real time.

---

## Executing Standalone Scripts (CLI Runner)

For standalone, single-execution PHP scripts that do not have an explicit autoloader entry point, run them directly with the TypePHP CLI binary:

```bash
vendor/bin/typephp script.php
```

---

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

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`:

```php
// typephp.php
return [
'include' => [
'*', // Intercepts and type-checks PHP files anywhere in the project
],
'exclude' => [
'vendor/**',
'storage/**',
'var/**',
'cache/**',
],
];
```

---

Expand Down Expand Up @@ -150,18 +230,26 @@ All the documentation lives on the **[typephp-php.github.io/docs website](https:
* [Official Blog & Announcements](https://typephp-php.github.io/docs/blog/)
* [Troubleshooting & FAQ](https://typephp-php.github.io/docs/troubleshooting)

---

## Inspiration

TypePHP is conceptually inspired by Python's [Beartype](https://github.com/beartype/beartype), bringing transparent runtime type enforcement for type annotations to the PHP ecosystem without any decorators or attributes.

---

## Sponsors

Want to support the open-source development and maintenance of TypePHP? [Sponsor me on GitHub »](https://github.com/sponsors/rcalicdan)

---

## Contributing

Any contributions are welcome. Feel free to open issues or submit pull requests on GitHub.

---

## License

TypePHP is open-source software licensed under the [MIT License](https://choosealicense.com/licenses/mit/).
13 changes: 13 additions & 0 deletions src/Command/ConfigInitCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,19 @@ private static function getTemplate(): string
*/
'array_validation' => 'full',

/*
|--------------------------------------------------------------------------
| Respect Native Parameter Nullability
|--------------------------------------------------------------------------
| When true (default), if a native PHP parameter explicitly declares
| nullable syntax (e.g. ?array $param = null), TypePHP permits null even
| if the DocBlock author omitted "|null" (e.g. @param string[] $param).
|
| Set to false for strict pedantic enforcement where DocBlocks are the
| absolute law and null is rejected unless explicitly typed in the DocBlock.
*/
'respect_native_nullability' => true,

/*
|--------------------------------------------------------------------------
| Enable Caching & Cache Directory
Expand Down
98 changes: 95 additions & 3 deletions src/Contract/ContractParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,7 @@ private static function parseMethod(\ReflectionMethod $ref): array
self::parseMethodHierarchyDocs($ref, $types, $methodTemplates, $returnType, $aliases);

if ($ref->getName() === '__construct') {
self::applyConstructorPromotionFallback($ref, $types);
self::applyConstructorPromotionFallback($ref, $types, $classTemplates);
}

return [
Expand Down Expand Up @@ -540,8 +540,10 @@ private static function parseFunction(\ReflectionFunction $ref): array

$baseParams = $ref->getParameters();
$baseParamVariadic = [];
$baseParamObjects = [];
foreach ($baseParams as $p) {
$baseParamVariadic[$p->getName()] = $p->isVariadic();
$baseParamObjects[$p->getName()] = $p;
}

foreach (DocblockExtractor::getParamTags($phpDocNode) as $paramName => $paramTag) {
Expand All @@ -554,6 +556,19 @@ private static function parseFunction(\ReflectionFunction $ref): array
) {
$type = new ArrayTypeNode($type);
}

$pObj = $baseParamObjects[$paramName] ?? null;
$isTemplateType = ($type instanceof IdentifierTypeNode && isset($templates[$type->name]));
if (
Config::isRespectNativeNullabilityEnabled()
&& $pObj !== null
&& self::parameterExplicitlyAllowsNull($pObj)
&& ! $isTemplateType
&& ! self::typeContainsNull($type)
) {
$type = new NullableTypeNode($type);
}

$substitutedType = self::substituteAliases($type, $aliases);
$resolvedType = SpecialTypeResolver::resolve($substitutedType, $ref);

Expand Down Expand Up @@ -650,12 +665,14 @@ private static function parseMethodHierarchyDocs(
$baseParamNames = [];
$baseParamSet = [];
$baseParamVariadic = [];
$baseParamObjects = [];
$isConstructor = ($ref->getName() === '__construct');

foreach ($baseParams as $idx => $p) {
$baseParamNames[$idx] = $p->getName();
$baseParamSet[$p->getName()] = $idx;
$baseParamVariadic[$p->getName()] = $p->isVariadic();
$baseParamObjects[$p->getName()] = $p;
}

foreach ($hierarchy as $hierRef) {
Expand Down Expand Up @@ -710,6 +727,19 @@ private static function parseMethodHierarchyDocs(
) {
$type = new ArrayTypeNode($type);
}

$pObj = $baseParamObjects[$targetParamName] ?? null;
$isTemplateType = ($type instanceof IdentifierTypeNode && isset($templates[$type->name]));
if (
Config::isRespectNativeNullabilityEnabled()
&& $pObj !== null
&& self::parameterExplicitlyAllowsNull($pObj)
&& ! $isTemplateType
&& ! self::typeContainsNull($type)
) {
$type = new NullableTypeNode($type);
}

$substitutedType = self::substituteAliases($type, $aliases);
$resolvedType = SpecialTypeResolver::resolve($substitutedType, $hierRef);

Expand Down Expand Up @@ -769,8 +799,9 @@ private static function resolveTargetParamName(
*
* @param \ReflectionMethod $ref
* @param array<string, TypeNode> $types
* @param array<string, TemplateTagValueNode> $classTemplates
*/
private static function applyConstructorPromotionFallback(\ReflectionMethod $ref, array &$types): void
private static function applyConstructorPromotionFallback(\ReflectionMethod $ref, array &$types, array $classTemplates = []): void
{
$declaringClass = $ref->getDeclaringClass();

Expand Down Expand Up @@ -811,6 +842,17 @@ private static function applyConstructorPromotionFallback(\ReflectionMethod $ref
) {
$propType = new ArrayTypeNode($propType);
}

$isTemplateType = ($propType instanceof IdentifierTypeNode && isset($classTemplates[$propType->name]));
if (
Config::isRespectNativeNullabilityEnabled()
&& self::parameterExplicitlyAllowsNull($p)
&& ! $isTemplateType
&& ! self::typeContainsNull($propType)
) {
$propType = new NullableTypeNode($propType);
}

$substitutedProp = self::substituteAliases($propType, []);
$resolvedProp = SpecialTypeResolver::resolve($substitutedProp, $ref);

Expand All @@ -825,6 +867,56 @@ private static function applyConstructorPromotionFallback(\ReflectionMethod $ref
}
}

/**
* Checks if a reflection parameter explicitly declares a nullable native typehint or default null value (excluding mixed).
*/
private static function parameterExplicitlyAllowsNull(\ReflectionParameter $p): bool
{
if (! $p->hasType()) {
return $p->isDefaultValueAvailable() && $p->getDefaultValue() === null;
}

$type = $p->getType();
if ($type instanceof \ReflectionNamedType) {
$name = strtolower($type->getName());
if ($name === 'mixed') {
return false;
}

return $type->allowsNull();
}

if ($type instanceof \ReflectionUnionType) {
return $type->allowsNull();
}

return false;
}

/**
* Checks if a TypeNode already represents or contains null.
*/
private static function typeContainsNull(TypeNode $node): bool
{
if ($node instanceof NullableTypeNode) {
return true;
}

if ($node instanceof IdentifierTypeNode && (\in_array(strtolower($node->name), ['null', 'mixed'], true))) {
return true;
}

if ($node instanceof UnionTypeNode) {
foreach ($node->types as $t) {
if (self::typeContainsNull($t)) {
return true;
}
}
}

return false;
}

/**
* Recursively substitutes all type aliases inside a TypeNode AST and simplifies unions/intersections containing `mixed`.
*
Expand Down Expand Up @@ -951,4 +1043,4 @@ public static function substituteAliases(TypeNode $node, array $aliases): TypeNo

return $node;
}
}
}
18 changes: 16 additions & 2 deletions src/Internal/CacheManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,30 @@ final class CacheManager
*/
public const VERSION_PREFIX = 'v0.1_';

/**
* Cached absolute cache directory path.
*/
private static ?string $resolvedCacheDir = null;

public static function reset(): void
{
self::$resolvedCacheDir = null;
}

/**
* Returns the absolute path to the cache directory, isolating by system user if using temp dir.
*/
public static function getCacheDir(): string
{
if (self::$resolvedCacheDir !== null) {
return self::$resolvedCacheDir;
}

$config = Config::get();
$dir = $config['cache_dir'] ?? null;

if (\is_string($dir) && $dir !== '') {
return $dir;
return self::$resolvedCacheDir = $dir;
}

$username = getenv('USERNAME');
Expand All @@ -43,7 +57,7 @@ public static function getCacheDir(): string

$userHash = hash('xxh128', 'typephp_' . $user);

return sys_get_temp_dir() . '/typephp-cache-' . $userHash;
return self::$resolvedCacheDir = sys_get_temp_dir() . '/typephp-cache-' . $userHash;
}

/**
Expand Down
Loading
Loading