Skip to content
Open
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
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
7 changes: 5 additions & 2 deletions docs/internals.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand All @@ -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.
Expand Down Expand Up @@ -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).
22 changes: 22 additions & 0 deletions docs/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -198,6 +205,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<EntityRow>`.
- `ActiveRowRelatedReturnTypeExtension` - `ActiveRow::related()` → `GroupedSelection<EntityRow>`
(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
Expand Down
32 changes: 32 additions & 0 deletions extension-nette.neon
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -22,13 +28,21 @@ parameters:
nette:
assets:
mapping: []
database:
mapping:
tables: []


parametersSchema:
nette: structure([
assets: structure([
mapping: arrayOf(string())
])
database: structure([
mapping: structure([
tables: arrayOf(string(), string())
])
])
])


Expand Down Expand Up @@ -67,6 +81,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
Expand Down
14 changes: 13 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<BookingRow>` instead of `Selection<ActiveRow>`, 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
Expand Down Expand Up @@ -72,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`).

Expand Down
102 changes: 102 additions & 0 deletions src/Database/ActiveRowRefReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?php declare(strict_types=1);

namespace Nette\PHPStan\Database;

use Nette\Database\Table\ActiveRow;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\{DynamicMethodReturnTypeExtension, NullType, Type, TypeCombinator};
use function count;


/**
* Narrows return type of ActiveRow::ref() from ?self
* to ?EntityRow based on table-to-entity-class mapping.
*
* When the foreign-key column (2nd argument) is declared as non-nullable on the
* calling row class, the referenced row is guaranteed to exist, so the result is
* narrowed to a non-nullable EntityRow.
*/
class ActiveRowRefReturnTypeExtension 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() === '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;
}
}
68 changes: 68 additions & 0 deletions src/Database/ActiveRowRelatedReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php declare(strict_types=1);

namespace Nette\PHPStan\Database;

use Nette\Database\Table\{ActiveRow, GroupedSelection};
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\{DynamicMethodReturnTypeExtension, Type};
use PHPStan\Type\Generic\GenericObjectType;
use function count;


/**
* Narrows return type of ActiveRow::related() from GroupedSelection<ActiveRow>
* to GroupedSelection<EntityRow> 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]);
}
}
68 changes: 68 additions & 0 deletions src/Database/ExplorerTableReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php declare(strict_types=1);

namespace Nette\PHPStan\Database;

use Nette\Database\Explorer;
use Nette\Database\Table\Selection;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\{DynamicMethodReturnTypeExtension, Type};
use PHPStan\Type\Generic\GenericObjectType;
use function count;


/**
* Narrows return type of Explorer::table() from Selection<ActiveRow>
* to Selection<EntityRow> 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]);
}
}
Loading