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..f933206 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -178,8 +178,10 @@ bootstrap files too) it does nothing. Side effect: PHPStan itself no longer sees `StaticMethodTypeSpecifyingExtension` + `TypeSpecifierAwareExtension`. Narrows variable types after `Tester\Assert` calls by mapping each assertion to an equivalent expression and delegating to `TypeSpecifier::specifyTypesInCondition()`. Supports `null`, `notNull`, `true`, `false`, -`truthy`, `falsey`, `same`, `notSame`, `type` (built-in type strings and class/interface names). -A shipped feature, not test-only. +`truthy`, `falsey`, `nan`, `same`, `notSame`, `count` (`array|Countable` with `count() === $n`), +`hasKey`/`hasNotKey` (`array_key_exists()`), `type` (built-in type strings including `list`, +class/interface names, a union of constant strings → `||` of the checks, or an object → +`instanceof` its class). A shipped feature, not test-only. ### Assets family (`MapperTypeResolver` shared service) @@ -198,6 +200,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..085e976 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 @@ -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()`, `count()`, `hasKey()`, etc. **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/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/src/Tester/AssertTypeNarrowingExtension.php b/src/Tester/AssertTypeNarrowingExtension.php index ebe57dd..0c58ff5 100644 --- a/src/Tester/AssertTypeNarrowingExtension.php +++ b/src/Tester/AssertTypeNarrowingExtension.php @@ -3,7 +3,7 @@ namespace Nette\PHPStan\Tester; use PhpParser\Node\{Arg, Expr, Name}; -use PhpParser\Node\Expr\BinaryOp\{Identical, NotIdentical}; +use PhpParser\Node\Expr\BinaryOp\{BooleanAnd, BooleanOr, Identical, NotIdentical}; use PhpParser\Node\Expr\{BooleanNot, ConstFetch, FuncCall, Instanceof_, StaticCall}; use PHPStan\Analyser\{Scope, SpecifiedTypes, TypeSpecifier, TypeSpecifierAwareExtension, TypeSpecifierContext}; use PHPStan\Reflection\MethodReflection; @@ -39,11 +39,22 @@ public function isStaticMethodSupported( ): bool { $minArgs = match ($staticMethodReflection->getName()) { - 'null', 'notNull', 'true', 'false', 'truthy', 'falsey' => 1, - 'same', 'notSame', 'type' => 2, + 'null', 'notNull', 'true', 'false', 'truthy', 'falsey', 'nan' => 1, + 'same', 'notSame', 'type', 'count', 'hasKey', 'hasNotKey' => 2, default => null, }; - return $minArgs !== null && count($node->getArgs()) >= $minArgs; + if ($minArgs === null || $node->isFirstClassCallable() || count($node->getArgs()) < $minArgs) { + return false; + } + + // named arguments are left unresolved only in an invalid call + foreach (array_slice($node->getArgs(), 0, $minArgs) as $arg) { + if ($arg->unpack || $arg->name !== null) { + return false; + } + } + + return true; } @@ -62,9 +73,22 @@ public function specifyTypes( 'false' => new Identical($args[0]->value, new ConstFetch(new Name('false'))), 'truthy' => $args[0]->value, 'falsey' => new BooleanNot($args[0]->value), + 'nan' => new BooleanAnd( + new FuncCall(new Name('is_float'), [$args[0]]), + new FuncCall(new Name('is_nan'), [$args[0]]), + ), 'same' => new Identical($args[1]->value, $args[0]->value), 'notSame' => new NotIdentical($args[1]->value, $args[0]->value), 'type' => $this->createTypeExpression($scope, $args), + 'count' => new BooleanAnd( + new BooleanOr( + new FuncCall(new Name('is_array'), [$args[1]]), + new Instanceof_($args[1]->value, new Name(\Countable::class)), + ), + new Identical(new FuncCall(new Name('count'), [$args[1]]), $args[0]->value), + ), + 'hasKey' => new FuncCall(new Name('array_key_exists'), [$args[0], $args[1]]), + 'hasNotKey' => new BooleanNot(new FuncCall(new Name('array_key_exists'), [$args[0], $args[1]])), default => null, }; @@ -81,41 +105,69 @@ public function specifyTypes( /** + * Type name strings (a union of them means any of the types) or an object (instanceof its class). * @param Arg[] $args */ private function createTypeExpression(Scope $scope, array $args): ?Expr { $typeType = $scope->getType($args[0]->value); - $constantStrings = $typeType->getConstantStrings(); - - if (count($constantStrings) === 1) { - $typeName = $constantStrings[0]->getValue(); - - $func = match ($typeName) { - 'list', 'array' => 'is_array', - 'bool' => 'is_bool', - 'callable' => 'is_callable', - 'float' => 'is_float', - 'int', 'integer' => 'is_int', - 'null' => 'is_null', - 'object' => 'is_object', - 'resource' => 'is_resource', - 'scalar' => 'is_scalar', - 'string' => 'is_string', - default => null, - }; - - return $func !== null - ? new FuncCall(new Name($func), [$args[1]]) - : new Instanceof_($args[1]->value, new Name($typeName)); + $checks = []; + + if ($typeType->isObject()->yes()) { + foreach ($typeType->getObjectClassNames() as $className) { + $checks[] = new Instanceof_($args[1]->value, new Name($className)); + } + } else { + foreach ($typeType->getConstantStrings() as $constantString) { + $check = $this->createTypeNameCheck($constantString->getValue(), $args[1]); + if ($check === null) { + return null; + } + $checks[] = $check; + } } - // object argument → instanceof using its class - $classNames = $typeType->getObjectClassNames(); - if (count($classNames) === 1) { - return new Instanceof_($args[1]->value, new Name($classNames[0])); + if (!$checks) { + return null; + } + + $expression = array_shift($checks); + foreach ($checks as $check) { + $expression = new BooleanOr($expression, $check); + } + return $expression; + } + + + private function createTypeNameCheck(string $typeName, Arg $value): ?Expr + { + if ($typeName === 'list') { + return new BooleanAnd( + new FuncCall(new Name('is_array'), [$value]), + new FuncCall(new Name('array_is_list'), [$value]), + ); + } + + $func = match ($typeName) { + 'array' => 'is_array', + 'bool' => 'is_bool', + 'callable' => 'is_callable', + 'float' => 'is_float', + 'int', 'integer' => 'is_int', + 'null' => 'is_null', + 'object' => 'is_object', + 'resource' => 'is_resource', + 'scalar' => 'is_scalar', + 'string' => 'is_string', + default => null, + }; + if ($func !== null) { + return new FuncCall(new Name($func), [$value]); } - return null; + $className = ltrim($typeName, '\\'); + return $className === '' + ? null + : new Instanceof_($value->value, new Name($className)); } } 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/Tester/assert-type-narrowing.php b/tests/Tester/assert-type-narrowing.php index fb5824e..da1dc77 100644 --- a/tests/Tester/assert-type-narrowing.php +++ b/tests/Tester/assert-type-narrowing.php @@ -126,7 +126,7 @@ function testTypeNull(int|string|null $val): void function testTypeList(mixed $val): void { Assert::type('list', $val); - assertType('array', $val); + assertType('list', $val); } @@ -142,3 +142,121 @@ function testTypeInterface(mixed $val): void Assert::type(Countable::class, $val); assertType('Countable', $val); } + + +function testTypeLeadingBackslash(mixed $val): void +{ + Assert::type('\\stdClass', $val); + assertType('stdClass', $val); +} + + +function testTypeEmptyString(mixed $val): void +{ + Assert::type('', $val); + assertType('mixed', $val); +} + + +/** + * @param array $args + */ +function testUnpackedArguments(array $args): void +{ + Assert::null(...$args); + assertType('array', $args); + + Assert::same(...$args); + assertType('array', $args); +} + + +function testNamedArguments(mixed $val): void +{ + Assert::null(description: 'must be null', actual: $val); + assertType('null', $val); +} + + +function testUnresolvableNamedArguments(?string $description): void +{ + Assert::null(description: $description); + assertType('string|null', $description); + + Assert::same(description: $description, expected: 1); + assertType('string|null', $description); +} + + +function testTypeUnion(mixed $val): void +{ + $type = rand(0, 1) ? 'int' : 'string'; + Assert::type($type, $val); + assertType('int|string', $val); +} + + +function testTypeObjectArgument(mixed $val): void +{ + Assert::type(new stdClass, $val); + assertType('stdClass', $val); +} + + +function testNan(mixed $val): void +{ + Assert::nan($val); + assertType('float', $val); +} + + +/** + * @param string[] $one + * @param int[] $none + */ +function testCount(array $one, array $none): void +{ + Assert::count(1, $one); + assertType('non-empty-array', $one); + + Assert::count(0, $none); + assertType('false', reset($none)); +} + + +/** + * @param array $val + */ +function testCountNamedArguments(array $val): void +{ + Assert::count(value: $val, count: 1); + assertType('non-empty-array', $val); +} + + +/** + * @param array{foo?: int, bar: string} $shape + * @param array $array + */ +function testHasKey(array $shape, array $array): void +{ + Assert::hasKey('foo', $shape); + assertType('array{foo: int, bar: string}', $shape); + + Assert::hasKey('foo', $array); + assertType("non-empty-array&hasOffset('foo')", $array); +} + + +/** + * @param array{foo?: int, bar: string} $shape + * @param array $array + */ +function testHasNotKey(array $shape, array $array): void +{ + Assert::hasNotKey('foo', $shape); + assertType('array{bar: string}', $shape); + + Assert::hasNotKey('foo', $array); + assertType('array', $array); +} 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');