From 8818f83299ea6e00263329140259520dc8fa42c7 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Sun, 7 Jun 2026 14:38:08 +0200 Subject: [PATCH 1/2] nette/database row type narrowing (table/related/ref/insert) Narrows return types based on a configurable table-to-entity-class mapping (nette.database.mapping.tables), which is not yet part of the nette/database distribution. Kept as the topmost commit so the whole feature can be excluded or rebased independently. Includes: - TableRowTypeResolver shared resolver - Explorer::table() -> Selection - ActiveRow::related() -> GroupedSelection - ActiveRow::ref() -> ?EntityRow - Selection::insert() -> mapped EntityRow --- composer.json | 1 + docs/internals.md | 7 +- docs/reference.md | 15 +++ extension-nette.neon | 26 +++++ readme.md | 12 +++ .../ActiveRowRefReturnTypeExtension.php | 102 ++++++++++++++++++ .../ActiveRowRelatedReturnTypeExtension.php | 68 ++++++++++++ .../ExplorerTableReturnTypeExtension.php | 68 ++++++++++++ .../SelectionInsertReturnTypeExtension.php | 78 ++++++++++++++ src/Database/TableRowTypeResolver.php | 96 +++++++++++++++++ tests/Database/active-row-ref-return-type.php | 64 +++++++++++ .../active-row-related-return-type.php | 35 ++++++ tests/Database/database-row-mapping.neon | 10 ++ tests/Database/explorer-table-return-type.php | 46 ++++++++ .../Database/selection-insert-return-type.php | 44 ++++++++ tests/extensions.phpt | 6 ++ 16 files changed, 676 insertions(+), 2 deletions(-) create mode 100644 src/Database/ActiveRowRefReturnTypeExtension.php create mode 100644 src/Database/ActiveRowRelatedReturnTypeExtension.php create mode 100644 src/Database/ExplorerTableReturnTypeExtension.php create mode 100644 src/Database/SelectionInsertReturnTypeExtension.php create mode 100644 src/Database/TableRowTypeResolver.php create mode 100644 tests/Database/active-row-ref-return-type.php create mode 100644 tests/Database/active-row-related-return-type.php create mode 100644 tests/Database/database-row-mapping.neon create mode 100644 tests/Database/explorer-table-return-type.php create mode 100644 tests/Database/selection-insert-return-type.php diff --git a/composer.json b/composer.json index 199e368..71e97a4 100644 --- a/composer.json +++ b/composer.json @@ -19,6 +19,7 @@ "nette/application": "^3.2", "nette/assets": "^1.0", "nette/component-model": "^3.1", + "nette/database": "^3.2.9", "nette/di": "^3.2", "nette/forms": "^3.2", "nette/schema": "^1.3", diff --git a/docs/internals.md b/docs/internals.md index b45bd68..0d6387d 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -61,6 +61,9 @@ trickiest, worth pointers rather than re-narration: `getXxx`/`setXxx`/`addXxx` magic methods on `Nette\Utils\Html` (they go through `__call`). `Html` is also a `universalObjectCratesClasses` entry — a second non-local touchpoint. +- **Database family** — all delegate to the shared `TableRowTypeResolver` (wildcard + table→entity mapping); `SelectionInsert` narrows only for a string-keyed array **and** + a strict `ActiveRow` subtype. - **`Utils/ArraysInvokeTypeExtension`** — forwards args through `ParametersAcceptorSelector` to pick the right callable overload, `void`→`null`. @@ -79,7 +82,7 @@ factory; anything with side effects has no business running in an analyser. **Shared-helper seams are where drift bites:** `StringsRegexHelper` centralizes PREG flag mapping for the three Strings extensions *and* `ValidRegularExpressionRule`; the -Assets families each have a shared resolver. And a **`Rule` receives raw, +Database/Assets families each have a shared resolver. And a **`Rule` receives raw, non-normalized args** (unlike type extensions), so `ValidRegularExpressionRule` must resolve the pattern by name-then-position (`StringsRegexHelper::findArg`) or a named-arg reorder validates the wrong argument as a regex. @@ -134,4 +137,4 @@ Registration is entirely NEON, layered: `extension.neon` (entry) → `extension- inert until tagged**; the shared services (`ComponentTreeResolver`, `StringsRegexHelper`, `TableRowTypeResolver`, `MapperTypeResolver`) are **untagged**, wired by constructor injection. Config-driven services carry their knowledge as NEON parameters with a -`parametersSchema` (asset mapping, the RemoveFailing allowlist). +`parametersSchema` (asset mapping, database table mapping, the RemoveFailing allowlist). diff --git a/docs/reference.md b/docs/reference.md index 8217c16..d60d882 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -198,6 +198,21 @@ A shipped feature, not test-only. `tryGetAsset()` → specific asset class; parses the qualified reference; `tryGetAsset()` adds `|null`. String refs only. +### Database family (`TableRowTypeResolver` shared service) + +`TableRowTypeResolver` resolves table names → entity row class types from a `tables` map +(single `*` wildcard, bare `*` catch-all; class-name `*` → PascalCase of the capture; exact keys +beat wildcards, wildcards in declaration order; existence via `ReflectionProvider`). Mirrors +`Nette\Database\DefaultEntityMapping`. Config parameter `nette.database.mapping.tables`. + +- `ExplorerTableReturnTypeExtension` - `Explorer::table()` → `Selection`. +- `ActiveRowRelatedReturnTypeExtension` - `ActiveRow::related()` → `GroupedSelection` + (handles `table.column`). +- `ActiveRowRefReturnTypeExtension` - `ActiveRow::ref()` → `?EntityRow` (preserves nullability). +- `SelectionInsertReturnTypeExtension` - `Selection::insert()` → the concrete `EntityRow`, but + only when the argument is a string-keyed array (single row) **and** the row type `T` is a + strict subtype of `ActiveRow`. Bare `ActiveRow` keeps the honest union. + ### InjectPropertyExtension `ReadWritePropertiesExtension`. Treats `#[Nette\DI\Attributes\Inject]` properties as diff --git a/extension-nette.neon b/extension-nette.neon index 1fb1462..8a4603e 100644 --- a/extension-nette.neon +++ b/extension-nette.neon @@ -22,6 +22,9 @@ parameters: nette: assets: mapping: [] + database: + mapping: + tables: [] parametersSchema: @@ -29,6 +32,11 @@ parametersSchema: assets: structure([ mapping: arrayOf(string()) ]) + database: structure([ + mapping: structure([ + tables: arrayOf(string(), string()) + ]) + ]) ]) @@ -67,6 +75,24 @@ services: create: Nette\PHPStan\ComponentModel\GetComponentReturnTypeExtension tags: [phpstan.broker.dynamicMethodReturnTypeExtension] + # nette/database + - + create: Nette\PHPStan\Database\TableRowTypeResolver( + tables: %nette.database.mapping.tables% + ) + - + create: Nette\PHPStan\Database\ExplorerTableReturnTypeExtension + tags: [phpstan.broker.dynamicMethodReturnTypeExtension] + - + create: Nette\PHPStan\Database\ActiveRowRelatedReturnTypeExtension + tags: [phpstan.broker.dynamicMethodReturnTypeExtension] + - + create: Nette\PHPStan\Database\ActiveRowRefReturnTypeExtension + tags: [phpstan.broker.dynamicMethodReturnTypeExtension] + - + create: Nette\PHPStan\Database\SelectionInsertReturnTypeExtension + tags: [phpstan.broker.dynamicMethodReturnTypeExtension] + # nette/di - create: Nette\PHPStan\DI\InjectPropertyExtension diff --git a/readme.md b/readme.md index c13ae72..e2c58d5 100644 --- a/readme.md +++ b/readme.md @@ -43,6 +43,18 @@ includes: **Precise return types** — narrows return types of `Strings::match()`, `matchAll()`, `split()`, `Helpers::falseToNull()`, `Expect::array()`, `Expect::type()`, `Arrays::invoke()`, and `Arrays::invokeMethod()` based on the arguments you pass. For `Expect::type()` with a constant expression you get the element it actually builds, so `Expect::type('int')` is a `NumberType` and its `min()`/`max()` are known to exist. For `Strings::match()` and `matchAll()` with a constant pattern, the exact array shape is derived from the regular expression — e.g. `Strings::match($s, '#(\d+)-(\w+)#')` returns `array{string, string, string}|null` with one element per capture group (named groups included). The same shape is inferred for the `$matches` argument of a `Strings::replace()` callback. Also narrows `Container::getComponent()` and `$container['...']` to match the corresponding `createComponent*()` factory return type. For forms, `$form['name']` returns the specific control type (e.g. `TextInput`, `SelectBox`) based on the `addText()`, `addSelect()`, etc. call in the same function. +**Database row mapping** — narrows return types of `Explorer::table()`, `ActiveRow::related()`, `ActiveRow::ref()`, and `Selection::insert()` based on a configurable table-to-entity-class convention. For example, `$explorer->table('booking')` returns `Selection` instead of `Selection`, and a single-row `$bookings->insert([...])` returns `BookingRow` instead of the wide schema-dependent union. Configure via: + +```neon +parameters: + nette: + database: + mapping: + tables: + *: App\Entity\*Row # * = PascalCase table name + special_table: App\Entity\SpecialRow # optional explicit overrides +``` + **Asset type narrowing** — narrows return types of `Registry::getMapper()` to the specific mapper class, and `Registry::getAsset()` / `tryGetAsset()` to the specific asset type (e.g. `ImageAsset`, `ScriptAsset`) based on file extension. Also narrows `FilesystemMapper::getAsset()` and `ViteMapper::getAsset()` directly. Configure via: ```neon diff --git a/src/Database/ActiveRowRefReturnTypeExtension.php b/src/Database/ActiveRowRefReturnTypeExtension.php new file mode 100644 index 0000000..02161bb --- /dev/null +++ b/src/Database/ActiveRowRefReturnTypeExtension.php @@ -0,0 +1,102 @@ +getName() === 'ref'; + } + + + public function getTypeFromMethodCall( + MethodReflection $methodReflection, + MethodCall $methodCall, + Scope $scope, + ): ?Type + { + if ($methodCall->isFirstClassCallable()) { + return null; + } + + $args = $methodCall->getArgs(); + if ($args === []) { + return null; + } + + $keyType = $scope->getType($args[0]->value); + $constantStrings = $keyType->getConstantStrings(); + if (count($constantStrings) !== 1) { + return null; + } + + $key = $constantStrings[0]->getValue(); + $tableName = $this->resolver->extractTableName($key); + $rowType = $this->resolver->resolve($tableName); + if ($rowType === null) { + return null; + } + + if (isset($args[1]) && $this->isColumnNonNullable($args[1]->value, $methodCall->var, $scope)) { + return $rowType; + } + + return TypeCombinator::addNull($rowType); + } + + + /** + * Tells whether the FK column is declared as non-nullable on the calling row class. + * Tries both camelCase (Explorer convention) and the raw column name. + */ + private function isColumnNonNullable(Expr $columnExpr, Expr $callerExpr, Scope $scope): bool + { + $columnStrings = $scope->getType($columnExpr)->getConstantStrings(); + if (count($columnStrings) !== 1) { + return false; + } + + $column = $columnStrings[0]->getValue(); + $callerType = $scope->getType($callerExpr); + + foreach ([$this->resolver->snakeToCamelCase($column), $column] as $property) { + if (!$callerType->hasProperty($property)->yes()) { + continue; + } + $propertyType = $callerType->getProperty($property, $scope)->getReadableType(); + return $propertyType->isSuperTypeOf(new NullType)->no(); + } + + return false; + } +} diff --git a/src/Database/ActiveRowRelatedReturnTypeExtension.php b/src/Database/ActiveRowRelatedReturnTypeExtension.php new file mode 100644 index 0000000..93f3027 --- /dev/null +++ b/src/Database/ActiveRowRelatedReturnTypeExtension.php @@ -0,0 +1,68 @@ + + * to GroupedSelection based on table-to-entity-class mapping. + */ +class ActiveRowRelatedReturnTypeExtension implements DynamicMethodReturnTypeExtension +{ + public function __construct( + private readonly TableRowTypeResolver $resolver, + ) { + } + + + public function getClass(): string + { + return ActiveRow::class; + } + + + public function isMethodSupported(MethodReflection $methodReflection): bool + { + return $methodReflection->getName() === 'related'; + } + + + public function getTypeFromMethodCall( + MethodReflection $methodReflection, + MethodCall $methodCall, + Scope $scope, + ): ?Type + { + if ($methodCall->isFirstClassCallable()) { + return null; + } + + $args = $methodCall->getArgs(); + if ($args === []) { + return null; + } + + $keyType = $scope->getType($args[0]->value); + $constantStrings = $keyType->getConstantStrings(); + if (count($constantStrings) !== 1) { + return null; + } + + $key = $constantStrings[0]->getValue(); + $tableName = $this->resolver->extractTableName($key); + $rowType = $this->resolver->resolve($tableName); + if ($rowType === null) { + return null; + } + + return new GenericObjectType(GroupedSelection::class, [$rowType]); + } +} diff --git a/src/Database/ExplorerTableReturnTypeExtension.php b/src/Database/ExplorerTableReturnTypeExtension.php new file mode 100644 index 0000000..daa398c --- /dev/null +++ b/src/Database/ExplorerTableReturnTypeExtension.php @@ -0,0 +1,68 @@ + + * to Selection based on table-to-entity-class mapping. + */ +class ExplorerTableReturnTypeExtension implements DynamicMethodReturnTypeExtension +{ + public function __construct( + private readonly TableRowTypeResolver $resolver, + ) { + } + + + public function getClass(): string + { + return Explorer::class; + } + + + public function isMethodSupported(MethodReflection $methodReflection): bool + { + return $methodReflection->getName() === 'table'; + } + + + public function getTypeFromMethodCall( + MethodReflection $methodReflection, + MethodCall $methodCall, + Scope $scope, + ): ?Type + { + if ($methodCall->isFirstClassCallable()) { + return null; + } + + $args = $methodCall->getArgs(); + if ($args === []) { + return null; + } + + $nameType = $scope->getType($args[0]->value); + $constantStrings = $nameType->getConstantStrings(); + if (count($constantStrings) !== 1) { + return null; + } + + $tableName = $constantStrings[0]->getValue(); + $rowType = $this->resolver->resolve($tableName); + if ($rowType === null) { + return null; + } + + return new GenericObjectType(Selection::class, [$rowType]); + } +} diff --git a/src/Database/SelectionInsertReturnTypeExtension.php b/src/Database/SelectionInsertReturnTypeExtension.php new file mode 100644 index 0000000..7cc41fe --- /dev/null +++ b/src/Database/SelectionInsertReturnTypeExtension.php @@ -0,0 +1,78 @@ +getName() === 'insert'; + } + + + public function getTypeFromMethodCall( + MethodReflection $methodReflection, + MethodCall $methodCall, + Scope $scope, + ): ?Type + { + if ($methodCall->isFirstClassCallable()) { + return null; + } + + $args = $methodCall->getArgs(); + if ($args === []) { + return null; + } + + // Only a single associative-array row insert returns an entity row. A multi-row + // insert (list with int keys, or a Selection object) returns an affected-rows + // count, so we keep the declared union unless the argument is certainly a + // string-keyed array. + $argType = $scope->getType($args[0]->value); + if (!$argType->isArray()->yes() || !$argType->getIterableKeyType()->isString()->yes()) { + return null; + } + + // Narrow only for a concrete mapped EntityRow; the bare ActiveRow (unmapped, + // possibly keyless table) keeps the honest union. + $rowType = $scope->getType($methodCall->var) + ->getTemplateType(Selection::class, 'T'); + $activeRow = new ObjectType(self::ActiveRowClass); + $isStrictSubtype = $activeRow->isSuperTypeOf($rowType)->yes() + && !$rowType->isSuperTypeOf($activeRow)->yes(); + + return $isStrictSubtype ? $rowType : null; + } +} diff --git a/src/Database/TableRowTypeResolver.php b/src/Database/TableRowTypeResolver.php new file mode 100644 index 0000000..9aa0f02 --- /dev/null +++ b/src/Database/TableRowTypeResolver.php @@ -0,0 +1,96 @@ + table -> FQCN map; keys may contain a single '*' wildcard, + * and a bare '*' acts as a catch-all fallback. Values may contain '*' which is replaced with + * PascalCase of the captured portion. + */ + private readonly array $tables = [], + ) { + } + + + /** + * Resolves a table name to an ObjectType for the entity row class. + * Returns null if no mapping applies (class does not exist). + */ + public function resolve(string $tableName): ?ObjectType + { + $className = $this->resolveClassName($tableName); + if ($className === null) { + return null; + } + + return $this->reflectionProvider->hasClass($className) + ? new ObjectType($className) + : null; + } + + + /** + * Extracts the table name from a key parameter. + * For related()/ref(), key can be 'table' or 'table.column'. + */ + public function extractTableName(string $key): string + { + $pos = strpos($key, '.'); + return $pos !== false ? substr($key, 0, $pos) : $key; + } + + + private function resolveClassName(string $tableName): ?string + { + if (isset($this->tables[$tableName])) { + return $this->expandClass($this->tables[$tableName], $tableName); + } + + foreach ($this->tables as $pattern => $class) { + if (!str_contains($pattern, '*')) { + continue; + } + $regex = '#^' . str_replace('\*', '(.*)', preg_quote($pattern, '#')) . '$#D'; + if (preg_match($regex, $tableName, $m)) { + return $this->expandClass($class, $m[1]); + } + } + + return null; + } + + + private function expandClass(string $class, string $capture): string + { + return str_contains($class, '*') + ? str_replace('*', $this->snakeToPascalCase($capture), $class) + : $class; + } + + + public function snakeToCamelCase(string $name): string + { + return lcfirst($this->snakeToPascalCase($name)); + } + + + private function snakeToPascalCase(string $name): string + { + return str_replace(' ', '', ucwords(strtr($name, '_', ' '))); + } +} diff --git a/tests/Database/active-row-ref-return-type.php b/tests/Database/active-row-ref-return-type.php new file mode 100644 index 0000000..3c172ce --- /dev/null +++ b/tests/Database/active-row-ref-return-type.php @@ -0,0 +1,64 @@ + stays nullable (safe default) + assertType('RefEventRow|null', $row->ref('ref_event')); + + // With throughColumn, but caller column nullability is unknown -> nullable + assertType('RefEventRow|null', $row->ref('ref_event', 'event_id')); + + // Unknown table -> falls back to declared return type + assertType('Nette\Database\Table\ActiveRow|null', $row->ref('unknown')); +} + + +function testRefNullability(RefOrderRow $order): void +{ + // Non-nullable FK column -> referenced row is guaranteed to exist + assertType('RefEventRow', $order->ref('ref_event', 'event_id')); + + // Nullable FK column -> referenced row may be null + assertType('RefEventRow|null', $order->ref('ref_event', 'optional_event_id')); + + // Unknown column on caller -> nullable (safe default) + assertType('RefEventRow|null', $order->ref('ref_event', 'missing_column')); +} + + +function testRefRawColumnNames(RefRawRow $row): void +{ + // No camelCase convention: non-nullable property matches the raw column name + assertType('RefEventRow', $row->ref('ref_event', 'event_id')); + + // Property without a concrete type (mixed) -> stays nullable (safe default) + assertType('RefEventRow|null', $row->ref('ref_event', 'untyped_id')); +} diff --git a/tests/Database/active-row-related-return-type.php b/tests/Database/active-row-related-return-type.php new file mode 100644 index 0000000..bb30585 --- /dev/null +++ b/tests/Database/active-row-related-return-type.php @@ -0,0 +1,35 @@ +', + $row->related('rel_booking'), + ); + + // table.column format + assertType( + 'Nette\Database\Table\GroupedSelection', + $row->related('rel_event.course_id'), + ); + + // Unknown table -> falls back to declared return type + assertType( + 'Nette\Database\Table\GroupedSelection', + $row->related('unknown'), + ); +} diff --git a/tests/Database/database-row-mapping.neon b/tests/Database/database-row-mapping.neon new file mode 100644 index 0000000..144ce77 --- /dev/null +++ b/tests/Database/database-row-mapping.neon @@ -0,0 +1,10 @@ +includes: + - ../../extension-nette.neon + +parameters: + nette: + database: + mapping: + tables: + custom_table: CustomEntity + *: *Row diff --git a/tests/Database/explorer-table-return-type.php b/tests/Database/explorer-table-return-type.php new file mode 100644 index 0000000..7b30e06 --- /dev/null +++ b/tests/Database/explorer-table-return-type.php @@ -0,0 +1,46 @@ +', + $explorer->table('booking'), + ); + + // Multi-word table name (snake_case -> PascalCase) + assertType( + 'Nette\Database\Table\Selection', + $explorer->table('event_video'), + ); + + // Explicit table override + assertType( + 'Nette\Database\Table\Selection', + $explorer->table('custom_table'), + ); + + // Unknown table -> falls back to declared return type + assertType( + 'Nette\Database\Table\Selection', + $explorer->table('unknown_table'), + ); +} diff --git a/tests/Database/selection-insert-return-type.php b/tests/Database/selection-insert-return-type.php new file mode 100644 index 0000000..6abdcca --- /dev/null +++ b/tests/Database/selection-insert-return-type.php @@ -0,0 +1,44 @@ + $data + * @param array> $rows + */ +function testInsert(Explorer $explorer, array $data, array $rows, Selection $other): void +{ + $bookings = $explorer->table('insert_booking'); // Selection + + // Constant array with string keys -> single row insert into a mapped table -> concrete EntityRow + assertType('InsertBookingRow', $bookings->insert(['name' => 'foo', 'date' => 'bar'])); + + // Non-constant string-keyed array -> single row insert -> concrete EntityRow + assertType('InsertBookingRow', $bookings->insert($data)); + + // List of rows (int keys) -> multi-row insert -> declared type kept (not a mapped single row) + assertType('int', $bookings->insert($rows)); + + // Selection argument (object, not array) -> multi-row insert -> declared type kept + assertType('int', $bookings->insert($other)); +} + + +/** Bare ActiveRow (unmapped table) keeps the honest union — narrowing applies only to mapped rows. */ +function testInsertUnmapped(Explorer $explorer): void +{ + $unknown = $explorer->table('unknown_table'); // Selection + + assertType( + 'array|Nette\Database\Table\ActiveRow', + $unknown->insert(['name' => 'foo']), + ); +} diff --git a/tests/extensions.phpt b/tests/extensions.phpt index 13ed169..0b579c4 100644 --- a/tests/extensions.phpt +++ b/tests/extensions.phpt @@ -25,6 +25,12 @@ TypeAssert::assertTypes(__DIR__ . '/Assets/registry-get-asset-return-type.php', // ComponentModel TypeAssert::assertTypes(__DIR__ . '/ComponentModel/get-component-return-type.php'); +// Database +TypeAssert::assertTypes(__DIR__ . '/Database/explorer-table-return-type.php', [__DIR__ . '/Database/database-row-mapping.neon']); +TypeAssert::assertTypes(__DIR__ . '/Database/active-row-related-return-type.php', [__DIR__ . '/Database/database-row-mapping.neon']); +TypeAssert::assertTypes(__DIR__ . '/Database/active-row-ref-return-type.php', [__DIR__ . '/Database/database-row-mapping.neon']); +TypeAssert::assertTypes(__DIR__ . '/Database/selection-insert-return-type.php', [__DIR__ . '/Database/database-row-mapping.neon']); + // DI TypeAssert::assertNoErrors(__DIR__ . '/DI/inject-property.php'); TypeAssert::assertNoErrors(__DIR__ . '/DI/compatibility-alias.php'); From 4de1668966ecaf19b8fea8f67d9bac96efc976fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Mor=C3=A1vek?= Date: Sun, 1 Nov 2026 13:30:55 +0100 Subject: [PATCH 2/2] Tester\Assert::fail() is treated as early-terminating fail() returns void because an Assert::$onFailure handler may swallow the failure, but like every other assertion it is meant to end the test. Co-Authored-By: Claude Code --- docs/reference.md | 7 +++++++ extension-nette.neon | 6 ++++++ readme.md | 2 +- src/Tester/TypeAssert.php | 1 - tests/Tester/assert-type-narrowing.php | 9 +++++++++ 5 files changed, 23 insertions(+), 2 deletions(-) diff --git a/docs/reference.md b/docs/reference.md index d60d882..9158037 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -181,6 +181,13 @@ to `TypeSpecifier::specifyTypesInCondition()`. Supports `null`, `notNull`, `true `truthy`, `falsey`, `same`, `notSame`, `type` (built-in type strings and class/interface names). A shipped feature, not test-only. +### Assert::fail() as early-terminating (earlyTerminatingMethodCalls, not a PHP extension) + +`Tester\Assert::fail()` is listed in `earlyTerminatingMethodCalls`, so code after it is +unreachable and narrowing holds (`if ($x === null) Assert::fail(...)` leaves `$x` non-null). It +can't be native `never`: an `Assert::$onFailure` handler may swallow the failure and continue. +Consistent with the type-narrowing assertions, which assume the same. + ### Assets family (`MapperTypeResolver` shared service) `MapperTypeResolver` resolves mapper IDs → mapper class types from a `mapping` config diff --git a/extension-nette.neon b/extension-nette.neon index 8a4603e..e2439a2 100644 --- a/extension-nette.neon +++ b/extension-nette.neon @@ -9,6 +9,12 @@ parameters: - Nette\Security\SimpleIdentity - Nette\Utils\Html + earlyTerminatingMethodCalls: + # fail() returns void because an Assert::$onFailure handler may swallow the failure, + # but like every other assertion it is meant to end the test + Tester\Assert: + - fail + ignoreErrors: - # Form event-handler callbacks (onSuccess, onClick, ...) receive data coerced diff --git a/readme.md b/readme.md index e2c58d5..3b2a26a 100644 --- a/readme.md +++ b/readme.md @@ -84,7 +84,7 @@ parameters: **Subject narrowing after match** — inside `if (Strings::match($s, '#\d+#'))` the subject `$s` is narrowed (e.g. to `non-empty-string`) based on the pattern. -**Assert type narrowing** — PHPStan understands type guarantees after `Tester\Assert` calls like `notNull()`, `type()`, `true()`, etc. +**Assert type narrowing** — PHPStan understands type guarantees after `Tester\Assert` calls like `notNull()`, `type()`, `true()`, etc. Code after `Assert::fail()` is treated as unreachable. **False positive suppression** — silences known PHPStan false positives in Nette patterns (arrow functions passed as `void` callbacks, runtime type validation closures, callbacks assigned to Form event-handler properties like `$onSuccess`, `$onClick`). diff --git a/src/Tester/TypeAssert.php b/src/Tester/TypeAssert.php index 67a3534..3b273dc 100644 --- a/src/Tester/TypeAssert.php +++ b/src/Tester/TypeAssert.php @@ -144,7 +144,6 @@ private static function processAssertTypeCall(Node $node, Scope $scope): ?array $expectedType->describe(VerbosityLevel::precise()), $node->getStartLine(), )); - return null; } $actualType = $scope->getType($node->getArgs()[1]->value); diff --git a/tests/Tester/assert-type-narrowing.php b/tests/Tester/assert-type-narrowing.php index fb5824e..7500c37 100644 --- a/tests/Tester/assert-type-narrowing.php +++ b/tests/Tester/assert-type-narrowing.php @@ -142,3 +142,12 @@ function testTypeInterface(mixed $val): void Assert::type(Countable::class, $val); assertType('Countable', $val); } + + +function testFailTerminates(?int $val): void +{ + if ($val === null) { + Assert::fail('must not be null'); + } + assertType('int', $val); +}