diff --git a/analyzer-baseline.toml b/analyzer-baseline.toml index 6525bc725..cbfcf7fe4 100644 --- a/analyzer-baseline.toml +++ b/analyzer-baseline.toml @@ -1,131 +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" -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/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" -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/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" @@ -156,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" @@ -240,12 +108,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" @@ -342,30 +204,12 @@ 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" 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" @@ -720,12 +564,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/lint-baseline.toml b/lint-baseline.toml index 19faa6c46..0e0e90aa2 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/mago.toml b/mago.toml index b803bde02..19a224af2 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/Adapter.php b/src/Adapter/Adapter.php index c507941b0..44b3da65a 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 d9321f579..8d488f09d 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 515c1c686..9bd38bd90 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 ed9382d72..f603d4be0 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/AbstractPdo.php b/src/Adapter/Driver/Pdo/AbstractPdo.php index 37a30e555..96948c94d 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/Driver/Pdo/AbstractPdoConnection.php b/src/Adapter/Driver/Pdo/AbstractPdoConnection.php index d49fac17a..28534ae84 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/Pdo/Result.php b/src/Adapter/Driver/Pdo/Result.php index 37a075050..43938f863 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/src/Adapter/Driver/StatementInterface.php b/src/Adapter/Driver/StatementInterface.php index de6c2d3c0..1d80f1fc4 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; diff --git a/src/Adapter/Exception/RuntimeException.php b/src/Adapter/Exception/RuntimeException.php index 88db28ecd..9de831145 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/src/Adapter/ParameterContainer.php b/src/Adapter/ParameterContainer.php index e9129797e..4322ffac4 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/src/Adapter/Profiler/Profiler.php b/src/Adapter/Profiler/Profiler.php index d4b5e82f5..79e3c9c30 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 diff --git a/src/Container/AbstractAdapterInterfaceFactory.php b/src/Container/AbstractAdapterInterfaceFactory.php index b596b0252..4c3a772ff 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/Container/AdapterInterfaceDelegator.php b/src/Container/AdapterInterfaceDelegator.php index 8213006e2..07884a210 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/Exception/ContainerException.php b/src/Exception/ContainerException.php index d6e7f2b09..7aa32c710 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/src/ResultSet/AbstractResultSet.php b/src/ResultSet/AbstractResultSet.php index 23ce8e53d..92033108b 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,6 +183,10 @@ public function getDataSource(): ?Iterator /** * Retrieve count of fields in individual rows of the result set * + * 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 */ #[Override] @@ -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/src/ResultSet/Exception/InvalidArgumentException.php b/src/ResultSet/Exception/InvalidArgumentException.php index 3757942e2..6e651538c 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 57b6553c0..03a907819 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 b36ce0037..e79860535 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; diff --git a/test/unit/Adapter/Container/AbstractAdapterInterfaceFactoryTest.php b/test/unit/Adapter/Container/AbstractAdapterInterfaceFactoryTest.php index 298529267..58c6fa0c6 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/Adapter/Driver/Pdo/PdoTest.php b/test/unit/Adapter/Driver/Pdo/PdoTest.php index 3a448073d..e7b098f2c 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/Driver/Pdo/ResultTest.php b/test/unit/Adapter/Driver/Pdo/ResultTest.php index 11cde0e9d..a2148861c 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 { diff --git a/test/unit/Adapter/Exception/RuntimeExceptionTest.php b/test/unit/Adapter/Exception/RuntimeExceptionTest.php index fc8984f24..84189b69b 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', [], diff --git a/test/unit/Adapter/ParameterContainerTest.php b/test/unit/Adapter/ParameterContainerTest.php index 474e8391c..c39b5e868 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 { diff --git a/test/unit/Exception/ContainerExceptionTest.php b/test/unit/Exception/ContainerExceptionTest.php index 45cb1d469..2ca7dc1f9 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 { diff --git a/test/unit/ResultSet/AbstractResultSetTest.php b/test/unit/ResultSet/AbstractResultSetTest.php index cc5af842e..3ce577631 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 {