Skip to content

Mago compliance: settle the API decisions behind remaining src analyzer issues - #255

Merged
simon-mundy merged 10 commits into
php-db:0.6.xfrom
simon-mundy:qa/mago-api-decisions
Nov 25, 2026
Merged

simon-mundy merged 10 commits into
php-db:0.6.xfrom
simon-mundy:qa/mago-api-decisions

Conversation

@simon-mundy

@simon-mundy simon-mundy commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Summary

Mago compliance, part 3 of 12. This PR covers the analyzer issues that needed an API decision rather than a mechanical fix, one decision per commit.

 interface StatementInterface / ResultInterface
-    public function getResource();
+    public function getResource(): mixed;
 AdapterInterface / Adapter
-    public function getHelpers();
+    public function getHelpers(): array;
 AbstractConnection
-    protected $resource;                   // redeclared by AbstractPdoConnection
+    protected mixed $resource = null;      // declared here only
 AbstractPdo
-    getResultPrototype(): ?ResultInterface
+    getResultPrototype(): ResultInterface  // throws RuntimeException::forMissingResultPrototype()
 AbstractAdapterInterfaceFactory
-    __invoke(ContainerInterface|ServiceManager $container)
+    __invoke(ContainerInterface $container) // throws ContainerException::forNonBuildingContainer()
 ParameterContainer
-    offsetGet(mixed $name) / offsetSet(mixed $name, …) / …
+    offsetGet(mixed $offset) / offsetSet(mixed $offset, …) / …
 Pdo\Result
-    next()
+    next(): void                           // properties typed too

Smaller changes:

  • Profiler's $profiles and $currentIndex properties are typed.
  • Classes meant for extension are tagged @api rather than made final.
  • AbstractResultSet::getFieldCount() no longer casts a mixed row to an array. It counts each kind of row explicitly, with the same results as the cast:
    • a Countable row: its count();
    • an array: its length;
    • an object: all of its properties, including non-public ones;
    • null: 0;
    • a scalar: 1.

Driver handle generics (resolves #170). The native handle types are now docblock templates. Each one is bounded by and defaults to object|resource, so code that uses the interfaces without type arguments sees no change.

ConnectionInterface<TConnection>                    getResource(): TConnection|null
StatementInterface<TStatement>                      getResource(): TStatement|false|null
ResultInterface<TResult>                            getResource(): TResult
DriverInterface<TConnection, TStatement, TResult>   createResult(), createStatement(), getConnection()

PdoDriverInterface      extends DriverInterface<PDO, PDOStatement, PDOStatement>
PdoConnectionInterface  extends ConnectionInterface<PDO>

Generics stop at the driver layer. docs/book/adapter.md shows how a driver package declares its types.

Evidence

Before (0.6.x) After
Analyzer baseline 197 entries 170 entries
Lint baseline — one halstead count in AbstractResultSet drops from 3 to 2
PdoDriverInterface->createStatement()->getResource() object|resource|false|null PDOStatement|false|null
PdoDriverInterface->getConnection()->getResource() object|resource|null PDO|null
DriverInterface->createStatement()->getResource() object|resource|false|null unchanged

Merge Danger

Door: one-way once released

The native return and property types are breaking changes for driver packages. Once a release ships them and the drivers adapt, reverting would break the drivers again. The generics are docblock-only and can be reverted freely.

Blast Radius: drivers

  • Subclasses that override getHelpers(), getResource(), getResultPrototype() or Pdo\Result::next() must declare the matching return type. An override of getResultPrototype() that still returns ?ResultInterface is a fatal error.
  • Subclasses that redeclare a newly typed property must declare the same type or drop the redeclaration: $resource as mixed in AbstractConnection, the Pdo\Result properties, and Profiler's $profiles and $currentIndex. Otherwise PHP raises a fatal error, because property types are invariant.
  • Code that used the value returned by Pdo\Result::next() now gets null. Read the row with current().
  • Code that calls Pdo\Result::getResource() before initialize() now gets an Error for the uninitialized property instead of null. Nothing in this repository does that, and phpdb-mysql's Result already behaves the same way.
  • Callers that use named arguments with ParameterContainer's offset*() methods need the new $offset name.
  • Code that relied on getResultPrototype() returning null now gets an exception.
  • Code that calls driver methods through PdoDriverInterface gets narrower types. Analyzers may now flag passing a non-PDOStatement to createResult(), or not handling false/null from Statement::getResource().

Driver follow-ups (after merge)

  • phpdb-mysql and phpdb-pgsql. Both redeclare $resource without a type in src/Connection.php:39. Change it to mixed or remove it.
  • All three drivers. Narrow $this->resource with instanceof PDO in Pdo\Connection.
  • All three drivers. Declare the handle types with @implements. For example, phpdb-mysql would use DriverInterface<mysqli, mysqli_stmt, mysqli|mysqli_result|mysqli_stmt>. Then remove the suppressions that cite Use @template generics on resource-typed interface members instead of the generic resource type #170.

Not in this PR

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.
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.
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.
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.
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 php-db#248.
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.
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.
@codecov

codecov Bot commented Nov 17, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The public contract documentation misrepresents fallback counting behavior, claims a nonexistent exception, and implies consistency with ObjectResultSet::toArray() that is not guaranteed.

1 open issue
What changed in this PR

This PR settles API decisions needed for Mago compliance across adapters, PDO results, containers, and result sets. It introduces explicit types and failure behavior while keeping designated extension points open.

Changes:

  • Adds native return and property types, and aligns ParameterContainer argument names with ArrayAccess.
  • Adds exceptions for missing result prototypes and unsupported containers, and replaces mixed-row casts with explicit field counting.
  • Marks extensible classes with @api, adds regression coverage, and removes resolved baseline entries.
File Description
test/​unit/​ResultSet/​AbstractResultSetTest.php Tests field counts for object, scalar, and null rows.
test/​unit/​Exception/​ContainerExceptionTest.php Tests the unsupported-container exception message.
test/​unit/​Adapter/​ParameterContainerTest.php Tests named offset arguments.
test/​unit/​Adapter/​Exception/​RuntimeExceptionTest.php Covers the missing-result-prototype exception.
test/​unit/​Adapter/​Driver/​Pdo/​ResultTest.php Tests generated-value types and iterator advancement.
test/​unit/​Adapter/​Driver/​Pdo/​PdoTest.php Tests failure when no result prototype is set.
test/​unit/​Adapter/​Container/​AbstractAdapterInterfaceFactoryTest.php Tests rejection of containers without dependency-building support.
src/​Sql/​Platform/​Platform.php Adds an @api annotation.
src/​ResultSet/​Exception/​RuntimeException.php Adds an @api annotation.
src/​ResultSet/​Exception/​InvalidArgumentException.php Adds an @api annotation.
src/​ResultSet/​AbstractResultSet.php Replaces row casts with explicit field-count branches.
src/​Exception/​ContainerException.php Adds the unsupported-container exception constructor.
src/​Container/​AdapterInterfaceDelegator.php Adds an @api annotation.
src/​Container/​AbstractAdapterInterfaceFactory.php Accepts ContainerInterface and checks building capability.
src/​Adapter/​Profiler/​Profiler.php Types profile storage and the current index.
src/​Adapter/​ParameterContainer.php Renames ArrayAccess parameters to offset.
src/​Adapter/​Exception/​RuntimeException.php Adds the missing-result-prototype exception constructor.
src/​Adapter/​Driver/​StatementInterface.php Declares a mixed resource return type.
src/​Adapter/​Driver/​Pdo/​Result.php Types result state and initialization; makes next() void.
src/​Adapter/​Driver/​Pdo/​AbstractPdoConnection.php Removes the inherited resource property's redeclaration.
src/​Adapter/​Driver/​Pdo/​AbstractPdo.php Returns a non-null prototype or throws.
src/​Adapter/​Driver/​ConnectionInterface.php Declares a mixed resource return type.
src/​Adapter/​Driver/​AbstractConnection.php Types the shared resource property and accessor.
src/​Adapter/​AdapterInterface.php Types the helper-list return contract.
src/​Adapter/​Adapter.php Adds the matching helper return type.
mago.toml Registers PDO result initialization with Mago.
lint-baseline.toml Reduces the result-set complexity suppression count.
analyzer-baseline.toml Removes resolved analyzer entries.

Review effort: Balanced

Comment thread src/ResultSet/AbstractResultSet.php Resolved
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.
Type the driver interfaces' native handles with template generics
ConnectionInterface, StatementInterface and ResultInterface each take a
template for the native handle their getResource() returns, and
DriverInterface takes all three for createResult(), createStatement()
and getConnection(). Each template is bounded by and defaults to
object|resource, so code that names the interfaces without type
arguments keeps the type it had.

A driver now states its real handle types with @implements instead of
suppressing mismatches against a generic resource type. The PDO drivers
get PDO, PDOStatement and PDOStatement through PdoDriverInterface and
PdoConnectionInterface, and AbstractConnection carries the connection
template down to AbstractPdoConnection.

The analyzer baseline entry for AdapterInterfaceFactory is reworded only:
its message now prints DriverInterface's default type arguments.

Closes php-db#170
@simon-mundy
simon-mundy requested a review from tyrsson November 25, 2026 01:51
@simon-mundy simon-mundy self-assigned this Nov 25, 2026
@simon-mundy simon-mundy added documentation Improvements or additions to documentation enhancement New feature or request qa Improvements in quality assurance of the project labels Nov 25, 2026
@github-project-automation github-project-automation Bot moved this to Todo in @phpdb Nov 25, 2026
@simon-mundy simon-mundy added this to the 0.6.0 milestone Nov 25, 2026
@github-project-automation github-project-automation Bot moved this from Todo to In Progress in @phpdb Nov 25, 2026
@simon-mundy
simon-mundy merged commit bdac3b0 into php-db:0.6.x Nov 25, 2026
15 checks passed
@github-project-automation github-project-automation Bot moved this from In Progress to Done in @phpdb Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation enhancement New feature or request qa Improvements in quality assurance of the project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Use @template generics on resource-typed interface members instead of the generic resource type

3 participants