From 9f974387d8193fcf70caacabe998fe8613e47d01 Mon Sep 17 00:00:00 2001 From: Simon Mundy Date: Tue, 17 Nov 2026 21:28:12 +1100 Subject: [PATCH 1/9] Declare native return types on getHelpers() and getResource() AdapterInterface::getHelpers() now returns array, and ConnectionInterface::getResource() and StatementInterface::getResource() return mixed, which every implementer must now declare. AbstractConnection::$resource is typed mixed with a null default: a native extension may still hand back a resource, which has no declarable type. Property types are invariant, so AbstractPdoConnection no longer redeclares the property to narrow it to PDO; it already narrows the handle where it reads it. --- analyzer-baseline.toml | 30 ------------------- src/Adapter/Adapter.php | 2 +- src/Adapter/AdapterInterface.php | 5 ++-- src/Adapter/Driver/AbstractConnection.php | 13 ++++++-- src/Adapter/Driver/ConnectionInterface.php | 2 +- .../Driver/Pdo/AbstractPdoConnection.php | 3 -- src/Adapter/Driver/StatementInterface.php | 4 +-- 7 files changed, 17 insertions(+), 42 deletions(-) diff --git a/analyzer-baseline.toml b/analyzer-baseline.toml index 6525bc72..10534467 100644 --- a/analyzer-baseline.toml +++ b/analyzer-baseline.toml @@ -1,29 +1,5 @@ variant = "loose" -[[issues]] -file = "src/Adapter/AdapterInterface.php" -code = "missing-return-type" -message = "Function `getHelpers` is missing a return type hint." -count = 1 - -[[issues]] -file = "src/Adapter/Driver/AbstractConnection.php" -code = "missing-property-type" -message = "Property `$resource` is missing a type hint." -count = 1 - -[[issues]] -file = "src/Adapter/Driver/AbstractConnection.php" -code = "mixed-return-statement" -message = 'Could not infer a precise return type for function `PhpDb\Adapter\Driver\AbstractConnection::getResource`. Saw type `mixed`.' -count = 1 - -[[issues]] -file = "src/Adapter/Driver/ConnectionInterface.php" -code = "missing-return-type" -message = "Function `getResource` is missing a return type hint." -count = 1 - [[issues]] file = "src/Adapter/Driver/Pdo/AbstractPdo.php" code = "overly-wide-return-type" @@ -84,12 +60,6 @@ code = "missing-property-type" message = "Property `$resource` is missing a type hint." count = 1 -[[issues]] -file = "src/Adapter/Driver/StatementInterface.php" -code = "missing-return-type" -message = "Function `getResource` is missing a return type hint." -count = 1 - [[issues]] file = "src/Adapter/ParameterContainer.php" code = "incompatible-parameter-name" diff --git a/src/Adapter/Adapter.php b/src/Adapter/Adapter.php index c507941b..44b3da65 100644 --- a/src/Adapter/Adapter.php +++ b/src/Adapter/Adapter.php @@ -99,7 +99,7 @@ public function getDriver(): Driver\DriverInterface * @mago-expect lint:prefer-first-class-callable */ #[Override] - public function getHelpers() + public function getHelpers(): array { $functions = []; $platform = $this->platform; diff --git a/src/Adapter/AdapterInterface.php b/src/Adapter/AdapterInterface.php index d9321f57..8d488f09 100644 --- a/src/Adapter/AdapterInterface.php +++ b/src/Adapter/AdapterInterface.php @@ -4,6 +4,7 @@ namespace PhpDb\Adapter; +use Closure; use PhpDb\ResultSet; /** @@ -51,9 +52,9 @@ public function getDriver(): Driver\DriverInterface; /** * @todo 0.3.x track down this usage!!! - * @return array + * @return list */ - public function getHelpers(); + public function getHelpers(): array; public function getPlatform(): Platform\PlatformInterface; diff --git a/src/Adapter/Driver/AbstractConnection.php b/src/Adapter/Driver/AbstractConnection.php index 515c1c68..9bd38bd9 100644 --- a/src/Adapter/Driver/AbstractConnection.php +++ b/src/Adapter/Driver/AbstractConnection.php @@ -27,8 +27,15 @@ abstract class AbstractConnection implements ConnectionInterface, ProfilerAwareI protected ?ProfilerInterface $profiler = null; - /** Extending classes must be covariant. */ - protected $resource; + /** + * The driver's native connection handle, or null while disconnected. It is typed mixed + * because a native extension may hand back a resource, which has no declarable type, and + * property types are invariant, so a driver narrows it where it reads it, not by + * redeclaring it. + * + * @var resource|object|null + */ + protected mixed $resource = null; #[Override] public function disconnect(): ConnectionInterface @@ -66,7 +73,7 @@ public function getProfiler(): ?ProfilerInterface * @return resource|object|null */ #[Override] - public function getResource() + public function getResource(): mixed { if (! $this->isConnected()) { $this->connect(); diff --git a/src/Adapter/Driver/ConnectionInterface.php b/src/Adapter/Driver/ConnectionInterface.php index ed9382d7..f603d4be 100644 --- a/src/Adapter/Driver/ConnectionInterface.php +++ b/src/Adapter/Driver/ConnectionInterface.php @@ -38,7 +38,7 @@ public function getLastGeneratedValue(?string $name = null): string|int|false|nu * * @return resource|object|null */ - public function getResource(); + public function getResource(): mixed; /** Checks whether the connection is in transaction state. */ public function inTransaction(): bool; diff --git a/src/Adapter/Driver/Pdo/AbstractPdoConnection.php b/src/Adapter/Driver/Pdo/AbstractPdoConnection.php index d49fac17..28534ae8 100644 --- a/src/Adapter/Driver/Pdo/AbstractPdoConnection.php +++ b/src/Adapter/Driver/Pdo/AbstractPdoConnection.php @@ -32,9 +32,6 @@ abstract class AbstractPdoConnection extends AbstractConnection implements protected ?string $dsn; - /** @var ?PDO $resource */ - protected $resource; - /** * {@inheritDoc} * diff --git a/src/Adapter/Driver/StatementInterface.php b/src/Adapter/Driver/StatementInterface.php index de6c2d3c..1d80f1fc 100644 --- a/src/Adapter/Driver/StatementInterface.php +++ b/src/Adapter/Driver/StatementInterface.php @@ -22,9 +22,9 @@ public function execute(ParameterContainer|array|null $parameters = null): ?Resu /** * Get resource * - * @return resource|false|null + * @return resource|object|false|null */ - public function getResource(); + public function getResource(): mixed; /** Check if is prepared */ public function isPrepared(): bool; From 3704b68f81050c5d685a5aff26d2808e0437983c Mon Sep 17 00:00:00 2001 From: Simon Mundy Date: Tue, 17 Nov 2026 21:28:42 +1100 Subject: [PATCH 2/9] Type Pdo\Result's properties and make next() return void The seven untyped properties are now natively typed, and initialize() declares string|int|false|null for the generated value. $resource is a non-nullable PDOStatement set by initialize(), which mago now treats as the class initializer. next() matches Iterator::next() and no longer returns the fetched row; read it with current(). No caller in the package used the returned row. --- analyzer-baseline.toml | 54 --------------------- mago.toml | 1 + src/Adapter/Driver/Pdo/Result.php | 50 ++++++------------- test/unit/Adapter/Driver/Pdo/ResultTest.php | 36 ++++++++++++++ 4 files changed, 52 insertions(+), 89 deletions(-) diff --git a/analyzer-baseline.toml b/analyzer-baseline.toml index 10534467..a56666e3 100644 --- a/analyzer-baseline.toml +++ b/analyzer-baseline.toml @@ -6,60 +6,6 @@ code = "overly-wide-return-type" message = 'Declared return type `PhpDb\Adapter\Driver\ResultInterface|null` for `getresultprototype` has unused branches: `null`.' count = 1 -[[issues]] -file = "src/Adapter/Driver/Pdo/Result.php" -code = "incompatible-return-type" -message = 'Return type `mixed` of `PhpDb\Adapter\Driver\Pdo\Result::next()` is incompatible with parent return type `void` of `Iterator::next()`' -count = 1 - -[[issues]] -file = "src/Adapter/Driver/Pdo/Result.php" -code = "missing-parameter-type" -message = "Parameter `$generatedValue` is missing a type hint." -count = 1 - -[[issues]] -file = "src/Adapter/Driver/Pdo/Result.php" -code = "missing-property-type" -message = "Property `$currentComplete` is missing a type hint." -count = 1 - -[[issues]] -file = "src/Adapter/Driver/Pdo/Result.php" -code = "missing-property-type" -message = "Property `$currentData` is missing a type hint." -count = 1 - -[[issues]] -file = "src/Adapter/Driver/Pdo/Result.php" -code = "missing-property-type" -message = "Property `$fetchMode` is missing a type hint." -count = 1 - -[[issues]] -file = "src/Adapter/Driver/Pdo/Result.php" -code = "missing-property-type" -message = "Property `$generatedValue` is missing a type hint." -count = 1 - -[[issues]] -file = "src/Adapter/Driver/Pdo/Result.php" -code = "missing-property-type" -message = "Property `$options` is missing a type hint." -count = 1 - -[[issues]] -file = "src/Adapter/Driver/Pdo/Result.php" -code = "missing-property-type" -message = "Property `$position` is missing a type hint." -count = 1 - -[[issues]] -file = "src/Adapter/Driver/Pdo/Result.php" -code = "missing-property-type" -message = "Property `$resource` is missing a type hint." -count = 1 - [[issues]] file = "src/Adapter/ParameterContainer.php" code = "incompatible-parameter-name" diff --git a/mago.toml b/mago.toml index b803bde0..19a224af 100644 --- a/mago.toml +++ b/mago.toml @@ -71,6 +71,7 @@ ignore = [ { code = "invalid-enum-case-value", in = ["src/Sql/ArgumentType.php"] }, ] class-initializers = [ + "PhpDb\\Adapter\\Driver\\Pdo\\Result::initialize", "PhpDb\\Adapter\\Driver\\Pdo\\Statement::initialize", "PhpDb\\Adapter\\Driver\\Pdo\\Statement::setDriver", "PhpDb\\ResultSet\\AbstractResultSet::initialize", diff --git a/src/Adapter/Driver/Pdo/Result.php b/src/Adapter/Driver/Pdo/Result.php index 37a07505..43938f86 100644 --- a/src/Adapter/Driver/Pdo/Result.php +++ b/src/Adapter/Driver/Pdo/Result.php @@ -33,8 +33,7 @@ class Result implements Iterator, ResultInterface protected string $statementMode = self::STATEMENT_MODE_FORWARD; - /** @var int */ - protected $fetchMode = PDO::FETCH_ASSOC; + protected int $fetchMode = PDO::FETCH_ASSOC; /** * @internal @@ -60,35 +59,22 @@ class Result implements Iterator, ResultInterface PDO::FETCH_CLASSTYPE, // Extra option for \PDO::FETCH_CLASS ]; - /** @var PDOStatement */ - protected $resource; + /** Set by initialize(); reading a result before then is an error. */ + protected PDOStatement $resource; - /** @var array Result options */ - protected $options; + /** @var array Result options */ + protected array $options = []; - /** - * Is the current complete? - * - * @var bool - */ - protected $currentComplete = false; + /** Is the current complete? */ + protected bool $currentComplete = false; - /** - * Track current item in recordset - * - * @var mixed - */ - protected $currentData; + /** Track current item in recordset */ + protected mixed $currentData = null; - /** - * Current position of scrollable statement - * - * @var int - */ - protected $position = -1; + /** Current position of scrollable statement */ + protected int $position = -1; - /** @var string|int|false|null */ - protected $generatedValue; + protected string|int|false|null $generatedValue = null; protected Closure|int|null $rowCount = null; @@ -202,12 +188,10 @@ public function getStatementMode(): string /** * Initialize - * - * @param string|int|false|null $generatedValue */ public function initialize( PDOStatement $resource, - $generatedValue, + string|int|false|null $generatedValue, Closure|int|null $rowCount = null, ): self { $this->resource = $resource; @@ -250,20 +234,16 @@ public function key() } /** - * Next - * - * @return mixed + * Fetch the next row and advance the position. Read the row with current(). * * @throws PDOException When the driver raises one while fetching. */ - #[ReturnTypeWillChange] #[Override] - public function next() + public function next(): void { $this->currentData = $this->resource->fetch($this->fetchMode); $this->currentComplete = true; $this->position++; - return $this->currentData; } /** diff --git a/test/unit/Adapter/Driver/Pdo/ResultTest.php b/test/unit/Adapter/Driver/Pdo/ResultTest.php index 11cde0e9..a2148861 100644 --- a/test/unit/Adapter/Driver/Pdo/ResultTest.php +++ b/test/unit/Adapter/Driver/Pdo/ResultTest.php @@ -12,6 +12,7 @@ use PhpDb\ResultSet\ResultSet; use PhpDbTest\TestAsset\TemporaryResultSet; use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -44,6 +45,17 @@ #[Group('unit')] final class ResultTest extends TestCase { + /** @return array */ + public static function generatedValueProvider(): array + { + return [ + 'string sequence value' => ['abc-123'], + 'integer insert id' => [7], + 'false from the driver' => [false], + 'no generated value' => [null], + ]; + } + #[Test] public function bufferIsCallableWithNoEffect(): void { @@ -294,6 +306,16 @@ public function getResourceReturnsPdoStatement(): void static::assertSame($stub, $result->getResource()); } + #[Test] + #[DataProvider('generatedValueProvider')] + public function initializeAcceptsEveryGeneratedValueType(string|int|false|null $generatedValue): void + { + $result = new Result(); + $result->initialize($this->createStub(PDOStatement::class), $generatedValue); + + static::assertSame($generatedValue, $result->getGeneratedValue()); + } + #[Test] public function initializeStoresResourceAndValues(): void { @@ -354,6 +376,20 @@ public function nextAdvancesPositionAndFetchesData(): void static::assertSame(1, $result->key()); } + #[Test] + public function nextFetchesTheRowThatCurrentThenReturns(): void + { + $stub = $this->createMock(PDOStatement::class); + $stub->expects($this->exactly(2))->method('fetch')->willReturn(['id' => 1], ['id' => 2]); + + $result = new Result(); + $result->initialize($stub, null); + $result->rewind(); + $result->next(); + + static::assertSame(['id' => 2], $result->current()); + } + #[Test] public function rewindResetsIterationToStart(): void { From a41888f1e4813470043ff91e03682cbeb2d51a21 Mon Sep 17 00:00:00 2001 From: Simon Mundy Date: Tue, 17 Nov 2026 21:28:42 +1100 Subject: [PATCH 3/9] Type Profiler's $profiles and $currentIndex properties --- analyzer-baseline.toml | 12 ------------ src/Adapter/Profiler/Profiler.php | 5 ++--- 2 files changed, 2 insertions(+), 15 deletions(-) diff --git a/analyzer-baseline.toml b/analyzer-baseline.toml index a56666e3..bcd12d36 100644 --- a/analyzer-baseline.toml +++ b/analyzer-baseline.toml @@ -30,18 +30,6 @@ code = "incompatible-parameter-name" message = 'Parameter #1 of `PhpDb\Adapter\ParameterContainer::offsetunset()` is named `$name` but parent `ArrayAccess::offsetunset()` names it `$offset`' count = 1 -[[issues]] -file = "src/Adapter/Profiler/Profiler.php" -code = "missing-property-type" -message = "Property `$currentIndex` is missing a type hint." -count = 1 - -[[issues]] -file = "src/Adapter/Profiler/Profiler.php" -code = "missing-property-type" -message = "Property `$profiles` is missing a type hint." -count = 1 - [[issues]] file = "src/ConfigProvider.php" code = "imprecise-type" diff --git a/src/Adapter/Profiler/Profiler.php b/src/Adapter/Profiler/Profiler.php index d4b5e82f..79e3c9c3 100644 --- a/src/Adapter/Profiler/Profiler.php +++ b/src/Adapter/Profiler/Profiler.php @@ -30,10 +30,9 @@ class Profiler implements ProfilerInterface { /** @var ProfilesShape */ - protected $profiles = []; + protected array $profiles = []; - /** @var int */ - protected $currentIndex = 0; + protected int $currentIndex = 0; /** * @return ProfileShape|null From ceddedb6911bf533efbb135a7d0053304010a56b Mon Sep 17 00:00:00 2001 From: Simon Mundy Date: Tue, 17 Nov 2026 21:28:43 +1100 Subject: [PATCH 4/9] Make AbstractPdo::getResultPrototype() non-nullable The prototype is set by the concrete driver, normally in its constructor. A driver that never sets it now gets RuntimeException::forMissingResultPrototype() instead of an uninitialised-property Error. --- analyzer-baseline.toml | 6 ------ src/Adapter/Driver/Pdo/AbstractPdo.php | 8 +++++--- src/Adapter/Exception/RuntimeException.php | 7 +++++++ test/unit/Adapter/Driver/Pdo/PdoTest.php | 12 ++++++++++++ test/unit/Adapter/Exception/RuntimeExceptionTest.php | 6 ++++++ 5 files changed, 30 insertions(+), 9 deletions(-) diff --git a/analyzer-baseline.toml b/analyzer-baseline.toml index bcd12d36..34cd321a 100644 --- a/analyzer-baseline.toml +++ b/analyzer-baseline.toml @@ -1,11 +1,5 @@ variant = "loose" -[[issues]] -file = "src/Adapter/Driver/Pdo/AbstractPdo.php" -code = "overly-wide-return-type" -message = 'Declared return type `PhpDb\Adapter\Driver\ResultInterface|null` for `getresultprototype` has unused branches: `null`.' -count = 1 - [[issues]] file = "src/Adapter/ParameterContainer.php" code = "incompatible-parameter-name" diff --git a/src/Adapter/Driver/Pdo/AbstractPdo.php b/src/Adapter/Driver/Pdo/AbstractPdo.php index 37a30e55..96948c94 100644 --- a/src/Adapter/Driver/Pdo/AbstractPdo.php +++ b/src/Adapter/Driver/Pdo/AbstractPdo.php @@ -145,11 +145,13 @@ public function getProfiler(): ?ProfilerInterface } /** - * {@inheritDoc} + * The concrete driver sets the prototype, normally in its constructor. + * + * @throws Exception\RuntimeException When the concrete driver has not set it. */ - public function getResultPrototype(): ?ResultInterface + public function getResultPrototype(): ResultInterface { - return $this->resultPrototype; + return $this->resultPrototype ?? throw Exception\RuntimeException::forMissingResultPrototype(); } #[Override] diff --git a/src/Adapter/Exception/RuntimeException.php b/src/Adapter/Exception/RuntimeException.php index 88db28ec..9de83114 100644 --- a/src/Adapter/Exception/RuntimeException.php +++ b/src/Adapter/Exception/RuntimeException.php @@ -43,6 +43,8 @@ class RuntimeException extends Exception\RuntimeException final public const string MISSING_QUERY_RESULT = 'Query execution did not produce a result'; + final public const string MISSING_RESULT_PROTOTYPE = 'No result prototype has been set on this driver'; + final public const string NON_QUERY_RESULT = 'Cannot produce a query result set from a result' . ' that is not a query result; check isQueryResult() first'; @@ -117,6 +119,11 @@ public static function forMissingQueryResult(): self return new self(self::MISSING_QUERY_RESULT); } + public static function forMissingResultPrototype(): self + { + return new self(self::MISSING_RESULT_PROTOTYPE); + } + public static function forNonQueryResult(): self { return new self(self::NON_QUERY_RESULT); diff --git a/test/unit/Adapter/Driver/Pdo/PdoTest.php b/test/unit/Adapter/Driver/Pdo/PdoTest.php index 3a448073..e7b098f2 100644 --- a/test/unit/Adapter/Driver/Pdo/PdoTest.php +++ b/test/unit/Adapter/Driver/Pdo/PdoTest.php @@ -26,6 +26,7 @@ use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use ReflectionClass; #[CoversMethod(AbstractPdo::class, 'getResultPrototype')] #[CoversMethod(AbstractPdo::class, 'checkEnvironment')] @@ -249,6 +250,17 @@ public function getResultPrototypeReturnsResult(): void static::assertInstanceOf(Result::class, $resultPrototype); } + #[Test] + public function getResultPrototypeThrowsWhenTheDriverHasNotSetIt(): void + { + $pdo = (new ReflectionClass(TestPdo::class))->newInstanceWithoutConstructor(); + + $this->expectException(AdapterRuntimeException::class); + $this->expectExceptionMessage(AdapterRuntimeException::MISSING_RESULT_PROTOTYPE); + + $pdo->getResultPrototype(); + } + #[Test] public function setProfilerPropagatesProfilerToConnectionAndStatement(): void { diff --git a/test/unit/Adapter/Exception/RuntimeExceptionTest.php b/test/unit/Adapter/Exception/RuntimeExceptionTest.php index fc8984f2..84189b69 100644 --- a/test/unit/Adapter/Exception/RuntimeExceptionTest.php +++ b/test/unit/Adapter/Exception/RuntimeExceptionTest.php @@ -29,6 +29,7 @@ #[CoversMethod(RuntimeException::class, 'forMissingDsn')] #[CoversMethod(RuntimeException::class, 'forMissingPdoExtension')] #[CoversMethod(RuntimeException::class, 'forMissingQueryResult')] +#[CoversMethod(RuntimeException::class, 'forMissingResultPrototype')] #[CoversMethod(RuntimeException::class, 'forNonQueryResult')] #[CoversMethod(RuntimeException::class, 'forRollbackWithoutTransaction')] #[CoversMethod(RuntimeException::class, 'forUncomposableTrait')] @@ -96,6 +97,11 @@ public static function namedConstructorProvider(): array [], RuntimeException::MISSING_QUERY_RESULT, ], + 'missing result prototype' => [ + 'forMissingResultPrototype', + [], + RuntimeException::MISSING_RESULT_PROTOTYPE, + ], 'non query result' => [ 'forNonQueryResult', [], From ba5e96e795be8762ec467088b3d39b72c02cd69c Mon Sep 17 00:00:00 2001 From: Simon Mundy Date: Tue, 17 Nov 2026 21:28:43 +1100 Subject: [PATCH 5/9] Name ParameterContainer's ArrayAccess parameter $offset offsetExists(), offsetGet(), offsetSet() and offsetUnset() now name their first parameter $offset, as ArrayAccess does, so a named argument works whether the container is typed as ParameterContainer or as ArrayAccess. A caller passing name: must pass offset: instead. --- analyzer-baseline.toml | 24 ---------- src/Adapter/ParameterContainer.php | 46 ++++++++++---------- test/unit/Adapter/ParameterContainerTest.php | 35 +++++++++++++++ 3 files changed, 59 insertions(+), 46 deletions(-) diff --git a/analyzer-baseline.toml b/analyzer-baseline.toml index 34cd321a..42bc3f62 100644 --- a/analyzer-baseline.toml +++ b/analyzer-baseline.toml @@ -1,29 +1,5 @@ variant = "loose" -[[issues]] -file = "src/Adapter/ParameterContainer.php" -code = "incompatible-parameter-name" -message = 'Parameter #1 of `PhpDb\Adapter\ParameterContainer::offsetexists()` is named `$name` but parent `ArrayAccess::offsetexists()` names it `$offset`' -count = 1 - -[[issues]] -file = "src/Adapter/ParameterContainer.php" -code = "incompatible-parameter-name" -message = 'Parameter #1 of `PhpDb\Adapter\ParameterContainer::offsetget()` is named `$name` but parent `ArrayAccess::offsetget()` names it `$offset`' -count = 1 - -[[issues]] -file = "src/Adapter/ParameterContainer.php" -code = "incompatible-parameter-name" -message = 'Parameter #1 of `PhpDb\Adapter\ParameterContainer::offsetset()` is named `$name` but parent `ArrayAccess::offsetset()` names it `$offset`' -count = 1 - -[[issues]] -file = "src/Adapter/ParameterContainer.php" -code = "incompatible-parameter-name" -message = 'Parameter #1 of `PhpDb\Adapter\ParameterContainer::offsetunset()` is named `$name` but parent `ArrayAccess::offsetunset()` names it `$offset`' -count = 1 - [[issues]] file = "src/ConfigProvider.php" code = "imprecise-type" diff --git a/src/Adapter/ParameterContainer.php b/src/Adapter/ParameterContainer.php index e9129797..4322ffac 100644 --- a/src/Adapter/ParameterContainer.php +++ b/src/Adapter/ParameterContainer.php @@ -162,13 +162,13 @@ public function next(): void /** * Offset exists * - * @param string|int $name + * @param string|int $offset */ #[Override] #[ReturnTypeWillChange] - public function offsetExists(mixed $name): bool + public function offsetExists(mixed $offset): bool { - return null !== ($this->data[$name] ?? null); + return null !== ($this->data[$offset] ?? null); } /** @@ -177,21 +177,21 @@ public function offsetExists(mixed $name): bool * A name that is not set is looked up again through the name mapping, without its * leading colon. * - * @param string|int $name + * @param string|int $offset */ #[Override] #[ReturnTypeWillChange] - public function offsetGet(mixed $name): mixed + public function offsetGet(mixed $offset): mixed { - if (null !== ($this->data[$name] ?? null)) { - return $this->data[$name]; + if (null !== ($this->data[$offset] ?? null)) { + return $this->data[$offset]; } - if (! is_string($name)) { + if (! is_string($offset)) { return null; } - $mappedName = $this->nameMapping[ltrim($name, characters: ':')] ?? null; + $mappedName = $this->nameMapping[ltrim($offset, characters: ':')] ?? null; return null === $mappedName ? null : $this->data[$mappedName] ?? null; } @@ -247,26 +247,28 @@ public function offsetHasMaxLength(string|int $name): bool * string name may be given with a leading colon, and either form follows the name mapping. * A null name appends a parameter named after the current count. Any other name is rejected. * - * @param mixed $name + * @param mixed $offset * @throws Exception\InvalidArgumentException */ #[Override] #[ReturnTypeWillChange] - public function offsetSet(mixed $name, mixed $value, mixed $errata = null, mixed $maxLength = null): void + public function offsetSet(mixed $offset, mixed $value, mixed $errata = null, mixed $maxLength = null): void { $key = match (true) { - is_int($name) => $this->positions[$name] ?? (string) $name, - is_string($name) => $this->nameMapping[str_starts_with($name, ':') ? substr($name, offset: 1) : $name] - ?? $name, - null === $name => (string) count($this->data), + is_int($offset) => $this->positions[$offset] ?? (string) $offset, + is_string($offset) => $this->nameMapping[str_starts_with($offset, ':') + ? substr($offset, offset: 1) + : $offset] + ?? $offset, + null === $offset => (string) count($this->data), default => throw Exception\InvalidArgumentException::forInvalidKeyType(), }; - $isNewPosition = is_int($name) - ? ! array_key_exists($name, $this->positions) + $isNewPosition = is_int($offset) + ? ! array_key_exists($offset, $this->positions) : null === ($this->data[$key] ?? null); - if (is_string($name) && is_string($value) && str_starts_with($value, ':')) { + if (is_string($offset) && is_string($value) && str_starts_with($value, ':')) { $this->nameMapping[substr($value, offset: 1)] = $key; } @@ -324,12 +326,12 @@ public function offsetSetReference(string|int $name, string|int $from): void */ #[Override] #[ReturnTypeWillChange] - public function offsetUnset(mixed $name): void + public function offsetUnset(mixed $offset): void { - if (is_int($name)) { - $name = $this->positions[$name] ?? $name; + if (is_int($offset)) { + $offset = $this->positions[$offset] ?? $offset; } - unset($this->data[$name]); + unset($this->data[$offset]); } /** diff --git a/test/unit/Adapter/ParameterContainerTest.php b/test/unit/Adapter/ParameterContainerTest.php index 474e8391..c39b5e86 100644 --- a/test/unit/Adapter/ParameterContainerTest.php +++ b/test/unit/Adapter/ParameterContainerTest.php @@ -48,6 +48,34 @@ final class ParameterContainerTest extends TestCase { protected ParameterContainer $parameterContainer; + /** @return array */ + public static function arrayAccessNamedOffsetProvider(): array + { + return [ + 'offsetExists' => [static fn(ParameterContainer $c): bool => $c->offsetExists(offset: 'foo'), true], + 'offsetGet' => [static fn(ParameterContainer $c): mixed => $c->offsetGet(offset: 'foo'), 'bar'], + 'offsetSet' => [ + static function (ParameterContainer $c): mixed { + $c->offsetSet( + offset: 'baz', + value: 'qux', + ); + + return $c->offsetGet('baz'); + }, + 'qux', + ], + 'offsetUnset' => [ + static function (ParameterContainer $c): bool { + $c->offsetUnset(offset: 'foo'); + + return $c->offsetExists('foo'); + }, + false, + ], + ]; + } + /** @return array */ public static function unknownPositionProvider(): array { @@ -77,6 +105,13 @@ static function (ParameterContainer $c): void { ]; } + #[Test] + #[DataProvider('arrayAccessNamedOffsetProvider')] + public function arrayAccessMethodsTakeTheOffsetNamedArgument(Closure $operation, mixed $expected): void + { + static::assertSame($expected, $operation($this->parameterContainer)); + } + #[Test] public function constructorWithDataPopulatesContainer(): void { From d81303a94d0c9370c6d0f5fe21118e63a3133e7a Mon Sep 17 00:00:00 2001 From: Simon Mundy Date: Tue, 17 Nov 2026 21:28:43 +1100 Subject: [PATCH 6/9] Tag extensible classes @api instead of making them final ResultSet\Exception\RuntimeException, ResultSet\Exception\InvalidArgumentException, Container\AdapterInterfaceDelegator and Sql\Platform\Platform stay open for extension and are marked as public API, as the Adapter classes were in #248. --- analyzer-baseline.toml | 24 ------------------- src/Container/AdapterInterfaceDelegator.php | 3 +++ .../Exception/InvalidArgumentException.php | 3 +++ src/ResultSet/Exception/RuntimeException.php | 3 +++ src/Sql/Platform/Platform.php | 3 +++ 5 files changed, 12 insertions(+), 24 deletions(-) diff --git a/analyzer-baseline.toml b/analyzer-baseline.toml index 42bc3f62..37251972 100644 --- a/analyzer-baseline.toml +++ b/analyzer-baseline.toml @@ -114,12 +114,6 @@ code = "unhandled-thrown-type" message = 'Potentially unhandled exception `Psr\Container\NotFoundExceptionInterface` in `PhpDb\Container\AbstractAdapterInterfaceFactory::getConfig`.' count = 1 -[[issues]] -file = "src/Container/AdapterInterfaceDelegator.php" -code = "class-must-be-final" -message = 'Class `PhpDb\Container\AdapterInterfaceDelegator` should be declared `final`.' -count = 1 - [[issues]] file = "src/Container/AdapterInterfaceDelegator.php" code = "imprecise-type" @@ -228,18 +222,6 @@ code = "mixed-assignment" message = "Assigning `mixed` type to a variable may lead to unexpected behavior." count = 2 -[[issues]] -file = "src/ResultSet/Exception/InvalidArgumentException.php" -code = "class-must-be-final" -message = 'Class `PhpDb\ResultSet\Exception\InvalidArgumentException` should be declared `final`.' -count = 1 - -[[issues]] -file = "src/ResultSet/Exception/RuntimeException.php" -code = "class-must-be-final" -message = 'Class `PhpDb\ResultSet\Exception\RuntimeException` should be declared `final`.' -count = 1 - [[issues]] file = "src/ResultSet/HydratingResultSet.php" code = "redundant-docblock-type" @@ -594,12 +576,6 @@ code = "non-existent-method" message = 'Method `prepareStatement` does not exist on type `PhpDb\Sql\SqlInterface`.' count = 1 -[[issues]] -file = "src/Sql/Platform/Platform.php" -code = "class-must-be-final" -message = 'Class `PhpDb\Sql\Platform\Platform` should be declared `final`.' -count = 1 - [[issues]] file = "src/Sql/Platform/Platform.php" code = "mixed-array-assignment" diff --git a/src/Container/AdapterInterfaceDelegator.php b/src/Container/AdapterInterfaceDelegator.php index 8213006e..07884a21 100644 --- a/src/Container/AdapterInterfaceDelegator.php +++ b/src/Container/AdapterInterfaceDelegator.php @@ -14,6 +14,9 @@ use function sprintf; +/** + * @api + */ class AdapterInterfaceDelegator { public function __construct( diff --git a/src/ResultSet/Exception/InvalidArgumentException.php b/src/ResultSet/Exception/InvalidArgumentException.php index 3757942e..6e651538 100644 --- a/src/ResultSet/Exception/InvalidArgumentException.php +++ b/src/ResultSet/Exception/InvalidArgumentException.php @@ -8,6 +8,9 @@ use function sprintf; +/** + * @api + */ class InvalidArgumentException extends Exception\InvalidArgumentException { final public const string UNRESOLVABLE_ITERATOR = 'The data source nests IteratorAggregate more than %d levels deep and cannot be resolved to an Iterator'; diff --git a/src/ResultSet/Exception/RuntimeException.php b/src/ResultSet/Exception/RuntimeException.php index 57b6553c..03a90781 100644 --- a/src/ResultSet/Exception/RuntimeException.php +++ b/src/ResultSet/Exception/RuntimeException.php @@ -6,6 +6,9 @@ use PhpDb\Exception; +/** + * @api + */ class RuntimeException extends Exception\RuntimeException { final public const string UNBUFFERED_ITERATION = 'Buffering must be enabled before iteration is started'; diff --git a/src/Sql/Platform/Platform.php b/src/Sql/Platform/Platform.php index b36ce003..e7986053 100644 --- a/src/Sql/Platform/Platform.php +++ b/src/Sql/Platform/Platform.php @@ -16,6 +16,9 @@ use function str_replace; use function strtolower; +/** + * @api + */ class Platform extends AbstractPlatform { protected PlatformInterface $defaultPlatform; From 72dc42ae9dfecb8f799fff35783bb651c95e00ea Mon Sep 17 00:00:00 2001 From: Simon Mundy Date: Tue, 17 Nov 2026 21:28:43 +1100 Subject: [PATCH 7/9] Accept FactoryInterface's container type in the abstract adapter factory AbstractAdapterInterfaceFactory::__invoke() now declares ContainerInterface, as FactoryInterface does, in place of ContainerInterface|ServiceManager and a docblock intersection with ServiceManager. It builds the adapter's dependencies with ServiceManager::build(), so any other container is refused with ContainerException::forNonBuildingContainer() instead of failing on an undefined method. --- analyzer-baseline.toml | 6 ----- .../AbstractAdapterInterfaceFactory.php | 9 +++++-- src/Exception/ContainerException.php | 10 ++++++++ .../AbstractAdapterInterfaceFactoryTest.php | 24 +++++++++++++++++++ .../unit/Exception/ContainerExceptionTest.php | 15 ++++++++++++ 5 files changed, 56 insertions(+), 8 deletions(-) diff --git a/analyzer-baseline.toml b/analyzer-baseline.toml index 37251972..f26e3d3f 100644 --- a/analyzer-baseline.toml +++ b/analyzer-baseline.toml @@ -30,12 +30,6 @@ code = "imprecise-type" message = "Type `array` in return type of `getConfig` is imprecise, equivalent to `array`." count = 1 -[[issues]] -file = "src/Container/AbstractAdapterInterfaceFactory.php" -code = "incompatible-parameter-type" -message = 'Parameter `$container` of `PhpDb\Container\AbstractAdapterInterfaceFactory::__invoke()` expects type `Psr\Container\ContainerInterface&Laminas\ServiceManager\ServiceManager` but parent `Laminas\ServiceManager\Factory\FactoryInterface::__invoke()` expects type `Psr\Container\ContainerInterface`' -count = 1 - [[issues]] file = "src/Container/AbstractAdapterInterfaceFactory.php" code = "invalid-return-statement" diff --git a/src/Container/AbstractAdapterInterfaceFactory.php b/src/Container/AbstractAdapterInterfaceFactory.php index b596b025..4c3a772f 100644 --- a/src/Container/AbstractAdapterInterfaceFactory.php +++ b/src/Container/AbstractAdapterInterfaceFactory.php @@ -75,12 +75,14 @@ protected function getConfig(ContainerInterface $container): array /** * Create a "Named" DB adapter * - * @phpstan-param ContainerInterface&ServiceManager $container + * The adapter's dependencies are built per adapter, so the container must be a + * ServiceManager. + * * @param string $requestedName */ #[Override] public function __invoke( - ContainerInterface|ServiceManager $container, + ContainerInterface $container, $requestedName, ?array $options = null, ): AdapterInterface&Adapter { @@ -90,6 +92,9 @@ public function __invoke( if (null === $driverClass) { throw ContainerException::forMissingDriver($requestedName, self::class); } + if (! $container instanceof ServiceManager) { + throw ContainerException::forNonBuildingContainer($requestedName, self::class, ServiceManager::class); + } /** @var DriverInterface|PdoDriverInterface $driver */ $driver = $container->build($driverClass, $this->config[$requestedName]); diff --git a/src/Exception/ContainerException.php b/src/Exception/ContainerException.php index d6e7f2b0..7aa32c71 100644 --- a/src/Exception/ContainerException.php +++ b/src/Exception/ContainerException.php @@ -25,6 +25,8 @@ final class ContainerException extends RuntimeException implements ContainerExce final public const string NON_ADAPTER_AWARE_DELEGATE = 'Delegated service "%s" must implement %s'; + final public const string NON_BUILDING_CONTAINER = 'the container must be a %s to build the adapter dependencies'; + final public const string SERVICE = 'Failed to create service "%s" in factory %s Reason: %s'; public static function forMissingConfigService(string $serviceName, string $factoryClass): self @@ -50,6 +52,14 @@ public static function forNonAdapterAwareDelegate(string $name, string $interfac return new self(sprintf(self::NON_ADAPTER_AWARE_DELEGATE, $name, $interface)); } + public static function forNonBuildingContainer( + string $serviceName, + string $factoryClass, + string $requiredClass, + ): self { + return self::forService($serviceName, $factoryClass, sprintf(self::NON_BUILDING_CONTAINER, $requiredClass)); + } + public static function forService( string $serviceName, string $factoryClass, diff --git a/test/unit/Adapter/Container/AbstractAdapterInterfaceFactoryTest.php b/test/unit/Adapter/Container/AbstractAdapterInterfaceFactoryTest.php index 29852926..58c6fa0c 100644 --- a/test/unit/Adapter/Container/AbstractAdapterInterfaceFactoryTest.php +++ b/test/unit/Adapter/Container/AbstractAdapterInterfaceFactoryTest.php @@ -26,6 +26,8 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function sprintf; + #[Group('unit')] #[CoversMethod(AbstractAdapterInterfaceFactory::class, 'canCreate')] #[CoversMethod(AbstractAdapterInterfaceFactory::class, '__invoke')] @@ -102,6 +104,28 @@ public function invalidService(string $service): void $this->serviceManager->get($service); } + #[Test] + public function invokeThrowsWhenContainerCannotBuildDependencies(): void + { + $container = $this->createStub(ContainerInterface::class); + $container->method('has')->willReturn(true); + $container->method('get') + ->willReturn([ + AdapterInterface::class => [ + 'adapters' => [ + 'MyAdapter' => ['driver' => PdoStubDriver::class], + ], + ], + ]); + + $factory = new AbstractAdapterInterfaceFactory(); + $factory->canCreate($container, 'MyAdapter'); + + self::expectException(ContainerException::class); + self::expectExceptionMessage(sprintf(ContainerException::NON_BUILDING_CONTAINER, ServiceManager::class)); + $factory($container, requestedName: 'MyAdapter'); + } + #[Test] public function invokeThrowsWhenDriverNotConfigured(): void { diff --git a/test/unit/Exception/ContainerExceptionTest.php b/test/unit/Exception/ContainerExceptionTest.php index 45cb1d46..2ca7dc1f 100644 --- a/test/unit/Exception/ContainerExceptionTest.php +++ b/test/unit/Exception/ContainerExceptionTest.php @@ -19,6 +19,7 @@ #[CoversMethod(ContainerException::class, 'forMissingConfiguration')] #[CoversMethod(ContainerException::class, 'forMissingDriver')] #[CoversMethod(ContainerException::class, 'forNonAdapterAwareDelegate')] +#[CoversMethod(ContainerException::class, 'forNonBuildingContainer')] #[CoversMethod(ContainerException::class, 'forService')] final class ContainerExceptionTest extends TestCase { @@ -68,6 +69,20 @@ public function forNonAdapterAwareDelegateRendersItsTemplate(): void ); } + #[Test] + public function forNonBuildingContainerComposesTheRequiredClassIntoTheServiceTemplate(): void + { + self::assertSame( + sprintf( + ContainerException::SERVICE, + 'Svc', + 'Factory', + sprintf(ContainerException::NON_BUILDING_CONTAINER, 'RequiredContainer'), + ), + ContainerException::forNonBuildingContainer('Svc', 'Factory', 'RequiredContainer')->getMessage(), + ); + } + #[Test] public function forServiceCreatesExceptionWithoutACode(): void { From 1a32f744e591b4b059520a9653311b28bf6439b3 Mon Sep 17 00:00:00 2001 From: Simon Mundy Date: Tue, 17 Nov 2026 21:28:44 +1100 Subject: [PATCH 8/9] Count AbstractResultSet's first row without casting mixed to array getFieldCount() cast the first row with (array), which the analyzer reports as an invalid cast from mixed. It now counts each kind of row explicitly, with the same results the cast gave: a Countable row by count(), an array by its length, an object through get_mangled_object_vars() (non-public properties included, as the cast counted them), null as 0 and any scalar as 1. --- analyzer-baseline.toml | 6 --- lint-baseline.toml | 2 +- src/ResultSet/AbstractResultSet.php | 20 ++++++--- test/unit/ResultSet/AbstractResultSetTest.php | 43 +++++++++++++++++++ 4 files changed, 58 insertions(+), 13 deletions(-) diff --git a/analyzer-baseline.toml b/analyzer-baseline.toml index f26e3d3f..cbfcf7fe 100644 --- a/analyzer-baseline.toml +++ b/analyzer-baseline.toml @@ -204,12 +204,6 @@ code = "incompatible-return-type" message = 'Return type `int|null` of `PhpDb\ResultSet\AbstractResultSet::count()` is incompatible with parent return type `int` of `Countable::count()`' count = 1 -[[issues]] -file = "src/ResultSet/AbstractResultSet.php" -code = "invalid-type-cast" -message = "Casting `mixed` to `array`." -count = 1 - [[issues]] file = "src/ResultSet/AbstractResultSet.php" code = "mixed-assignment" diff --git a/lint-baseline.toml b/lint-baseline.toml index 19faa6c4..0e0e90aa 100644 --- a/lint-baseline.toml +++ b/lint-baseline.toml @@ -28,7 +28,7 @@ count = 1 file = "src/ResultSet/AbstractResultSet.php" code = "halstead" message = "Method has a high halstead difficulty" -count = 3 +count = 2 [[issues]] file = "src/ResultSet/AbstractResultSet.php" diff --git a/src/ResultSet/AbstractResultSet.php b/src/ResultSet/AbstractResultSet.php index 23ce8e53..944a434e 100644 --- a/src/ResultSet/AbstractResultSet.php +++ b/src/ResultSet/AbstractResultSet.php @@ -21,7 +21,9 @@ use function count; use function current; use function get_debug_type; +use function get_mangled_object_vars; use function is_array; +use function is_object; use function reset; /** @@ -181,7 +183,11 @@ public function getDataSource(): ?Iterator /** * Retrieve count of fields in individual rows of the result set * + * The first row is counted: a Countable row by its count(), an array by its elements and + * any other object by its public properties, as ObjectResultSet::toArray() reads them. + * * @throws RuntimeException + * @throws UnexpectedValueException If the first row is a scalar or null, which has no fields. */ #[Override] public function getFieldCount(): int @@ -203,13 +209,15 @@ public function getFieldCount(): int } $row = $dataSource->current(); - if ($row instanceof Countable) { - $this->fieldCount = $row->count(); - return $this->fieldCount; - } - $row = (array) $row; - $this->fieldCount = count($row); + $this->fieldCount = match (true) { + $row instanceof Countable => $row->count(), + is_array($row) => count($row), + is_object($row) => count(get_mangled_object_vars($row)), + null === $row => 0, + default => 1, + }; + return $this->fieldCount; } diff --git a/test/unit/ResultSet/AbstractResultSetTest.php b/test/unit/ResultSet/AbstractResultSetTest.php index cc5af842..3ce57763 100644 --- a/test/unit/ResultSet/AbstractResultSetTest.php +++ b/test/unit/ResultSet/AbstractResultSetTest.php @@ -18,9 +18,11 @@ use PhpDb\ResultSet\Exception\RuntimeException; use PhpDbTest\ResultSet\TestAsset\PassThroughResultSet; use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use stdClass; use TypeError; use function assert; @@ -46,6 +48,24 @@ final class AbstractResultSetTest extends TestCase { protected AbstractResultSet $resultSet; + /** @return array */ + public static function nonArrayRowProvider(): array + { + return [ + 'null row' => [null, 0], + 'boolean row' => [true, 1], + 'integer row' => [42, 1], + 'string row' => ['value', 1], + 'object row with non-public properties' => [new class { + public int $id = 1; + + protected string $name = 'one'; + + private string $label = 'two'; + }, 3], + ]; + } + /** * @throws Exception */ @@ -372,6 +392,29 @@ public function getFieldCount(): void static::assertSame(2, $resultSet->getFieldCount()); } + #[Test] + #[DataProvider('nonArrayRowProvider')] + public function getFieldCountCountsANonArrayRowAsAnArrayCastWould(mixed $row, int $expected): void + { + $resultSet = $this->createResultSetMock(); + $resultSet->initialize(new ArrayIterator([$row])); + + static::assertSame($expected, $resultSet->getFieldCount()); + } + + #[Test] + public function getFieldCountCountsThePublicPropertiesOfAnObjectRow(): void + { + $row = new stdClass(); + $row->id = 1; + $row->name = 'one'; + + $resultSet = $this->createResultSetMock(); + $resultSet->initialize(new ArrayIterator([$row])); + + static::assertSame(2, $resultSet->getFieldCount()); + } + #[Test] public function getFieldCountReturnsCachedValue(): void { From b8b1e19eb74650b74d4da75e0071fc0817fe220a Mon Sep 17 00:00:00 2001 From: Simon Mundy Date: Wed, 18 Nov 2026 10:44:30 +1100 Subject: [PATCH 9/9] Describe getFieldCount()'s counting as it is implemented The docblock still described an earlier version: it said objects were counted by their public properties and that scalar or null rows threw UnexpectedValueException. The method counts every property of an object, null as 0 and any other scalar as 1, the same as the (array) cast it replaced, and throws no UnexpectedValueException. --- src/ResultSet/AbstractResultSet.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ResultSet/AbstractResultSet.php b/src/ResultSet/AbstractResultSet.php index 944a434e..92033108 100644 --- a/src/ResultSet/AbstractResultSet.php +++ b/src/ResultSet/AbstractResultSet.php @@ -183,11 +183,11 @@ public function getDataSource(): ?Iterator /** * Retrieve count of fields in individual rows of the result set * - * The first row is counted: a Countable row by its count(), an array by its elements and - * any other object by its public properties, as ObjectResultSet::toArray() reads them. + * The first row is counted as an (array) cast would count it: a Countable row by its + * count(), an array by its elements, any other object by all of its properties + * (non-public ones included), null as 0 and any other scalar as 1. * * @throws RuntimeException - * @throws UnexpectedValueException If the first row is a scalar or null, which has no fields. */ #[Override] public function getFieldCount(): int