diff --git a/src/Sql/Exception/InvalidArgumentException.php b/src/Sql/Exception/InvalidArgumentException.php index a73237b8..547275e3 100644 --- a/src/Sql/Exception/InvalidArgumentException.php +++ b/src/Sql/Exception/InvalidArgumentException.php @@ -74,6 +74,11 @@ class InvalidArgumentException extends Exception\InvalidArgumentException 'A PhpDb\Sql\Select instance cannot be provided' . ' with the merge flag'; + final public const string TYPED_EXPRESSION_PARAMETER = + 'Expression parameter ["%s" => "%s"] uses the typed form, which is not supported;' + . ' pass a PhpDb\Sql\Argument\Identifier, Argument\Value, Argument\Literal or Argument\Select' + . ' instead, for example Argument::identifier(), or a list for IN (?)'; + final public const string UNENCLOSED_VALUES_PLACEHOLDER = 'An array or Values parameter in the expression "%s" must use a placeholder' . ' wrapped in its own parentheses, such as IN (?)'; @@ -203,6 +208,11 @@ public static function forSelectWithMergeFlag(): self return new self(self::SELECT_WITH_MERGE_FLAG); } + public static function forTypedExpressionParameter(string $key, string $type): self + { + return new self(sprintf(self::TYPED_EXPRESSION_PARAMETER, $key, $type)); + } + public static function forUnenclosedValuesPlaceholder(string $expression): self { return new self(sprintf(self::UNENCLOSED_VALUES_PLACEHOLDER, $expression)); diff --git a/src/Sql/Expression.php b/src/Sql/Expression.php index 67e45921..67878542 100644 --- a/src/Sql/Expression.php +++ b/src/Sql/Expression.php @@ -13,10 +13,13 @@ use function array_slice; use function array_unique; use function count; +use function current; use function explode; use function func_get_args; use function func_num_args; +use function in_array; use function is_array; +use function key; use function preg_match; use function preg_match_all; use function str_replace; @@ -25,6 +28,11 @@ /** * @api * + * Refusing the typed parameter form `[value => type]` adds the branches that take the class over the complexity limit; + * the check belongs where those parameters arrive, so the limit is accepted here rather than split into a helper. + * + * @mago-expect lint:cyclomatic-complexity + * * @psalm-type ExpressionParameter = bool|string|float|int|null|list|ExpressionInterface|ArgumentInterface */ class Expression extends AbstractExpression @@ -34,6 +42,8 @@ class Expression extends AbstractExpression */ final public const string PLACEHOLDER = '?'; + private const array TYPE_NAMES = ['identifier', 'value', 'literal', 'select']; + protected string $expression = ''; /** @var list */ @@ -143,7 +153,7 @@ public function setParameters( foreach ($parameters as $parameter) { $this->parameters[] = match (true) { - is_array($parameter) => new Values($parameter), + is_array($parameter) => new Values($this->validTypedParameter($parameter)), $parameter instanceof ExpressionInterface => new SelectArgument($parameter), $parameter instanceof ArgumentInterface => $parameter, default => new Value($parameter), @@ -182,4 +192,31 @@ private function placeholderFor(?ArgumentInterface $parameter, string $before, s return substr($parameter->getSpecification(), offset: 1, length: -1); } + + /** + * Returns an array parameter as the list it binds, refusing the typed form `[value => type]` + * + * A single-entry array whose key is not 0 and whose value is a type name has the typed form. Bound as a list + * it would render the type name, so it fails loudly instead; lists such as `['identifier']` are returned + * unchanged. + * + * @param list $parameter + * @return list + * @throws Exception\InvalidArgumentException + */ + private function validTypedParameter(array $parameter): array + { + if ( + 1 === count($parameter) + && 0 !== key($parameter) + && in_array(current($parameter), self::TYPE_NAMES, strict: true) + ) { + throw Exception\InvalidArgumentException::forTypedExpressionParameter( + (string) key($parameter), + (string) current($parameter), + ); + } + + return $parameter; + } } diff --git a/test/unit/Sql/Exception/InvalidArgumentExceptionTest.php b/test/unit/Sql/Exception/InvalidArgumentExceptionTest.php index 2ba7e797..95955012 100644 --- a/test/unit/Sql/Exception/InvalidArgumentExceptionTest.php +++ b/test/unit/Sql/Exception/InvalidArgumentExceptionTest.php @@ -39,6 +39,7 @@ #[CoversMethod(InvalidArgumentException::class, 'forNonStringValueKey')] #[CoversMethod(InvalidArgumentException::class, 'forReadOnlyConstructorState')] #[CoversMethod(InvalidArgumentException::class, 'forSelectWithMergeFlag')] +#[CoversMethod(InvalidArgumentException::class, 'forTypedExpressionParameter')] #[CoversMethod(InvalidArgumentException::class, 'forUnenclosedValuesPlaceholder')] #[CoversMethod(InvalidArgumentException::class, 'forUnknownArgumentType')] #[CoversMethod(InvalidArgumentException::class, 'forUnquotableIdentifier')] @@ -173,6 +174,11 @@ public static function namedConstructorProvider(): array [], InvalidArgumentException::SELECT_WITH_MERGE_FLAG, ], + 'typed expression parameter' => [ + 'forTypedExpressionParameter', + ['a', 'identifier'], + InvalidArgumentException::TYPED_EXPRESSION_PARAMETER, + ], 'unenclosed values placeholder' => [ 'forUnenclosedValuesPlaceholder', ['a IN ?'], diff --git a/test/unit/Sql/ExpressionTest.php b/test/unit/Sql/ExpressionTest.php index b30b837e..68183a0f 100644 --- a/test/unit/Sql/ExpressionTest.php +++ b/test/unit/Sql/ExpressionTest.php @@ -8,6 +8,8 @@ use PhpDb\Sql\Argument\Identifier; use PhpDb\Sql\Argument\Literal; use PhpDb\Sql\Argument\Value; +use PhpDb\Sql\Argument\Values; +use PhpDb\Sql\ArgumentInterface; use PhpDb\Sql\Exception\InvalidArgumentException; use PhpDb\Sql\Exception\RuntimeException; use PhpDb\Sql\Expression; @@ -33,6 +35,7 @@ #[CoversMethod(Expression::class, 'getParameters')] #[CoversMethod(Expression::class, 'getExpressionData')] #[CoversMethod(Expression::class, 'placeholderFor')] +#[CoversMethod(Expression::class, 'validTypedParameter')] #[CoversMethod(Expression::class, 'setSpecification')] #[Group('unit')] final class ExpressionTest extends TestCase @@ -65,6 +68,21 @@ public static function falsyExpressionParametersProvider(): array ]; } + /** @return array, string, string}> */ + public static function typedParameterProvider(): array + { + return [ + 'string key identifier' => [['a' => 'identifier'], 'a', 'identifier'], + 'string key value' => [['a' => 'value'], 'a', 'value'], + 'string key literal' => [['a' => 'literal'], 'a', 'literal'], + 'string key select' => [['a' => 'select'], 'a', 'select'], + 'integer key identifier' => [[5 => 'identifier'], '5', 'identifier'], + 'integer key value' => [[5 => 'value'], '5', 'value'], + 'integer key literal' => [[5 => 'literal'], '5', 'literal'], + 'integer key select' => [[5 => 'select'], '5', 'select'], + ]; + } + /** @return array}> */ public static function unenclosedArrayParameterProvider(): array { @@ -78,6 +96,33 @@ public static function unenclosedArrayParameterProvider(): array ]; } + /** @return array */ + public static function untypedParameterProvider(): array + { + return [ + 'plain list' => [[1, 2, 3], new Values([1, 2, 3])], + 'list holding a type name' => [['identifier'], new Values(['identifier'])], + 'list with gapped keys' => [[1 => 'x', 2 => 'y'], new Values(['x', 'y'])], + 'single entry, not a type' => [['a' => 'b'], new Values(['b'])], + 'two entries holding types' => [['a' => 'identifier', 'b' => 'value'], new Values(['identifier', 'value'])], + 'string scalar of a type name' => ['identifier', new Value('identifier')], + 'integer scalar' => [5, new Value(5)], + 'identifier argument' => [Argument::identifier('a'), Argument::identifier('a')], + 'value argument' => [Argument::value('a'), Argument::value('a')], + 'literal argument' => [Argument::literal('NOW()'), Argument::literal('NOW()')], + ]; + } + + #[Test] + #[DataProvider('typedParameterProvider')] + public function constructorRejectsTypedParameter(array $parameter, string $key, string $type): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(sprintf(InvalidArgumentException::TYPED_EXPRESSION_PARAMETER, $key, $type)); + + new Expression('UPPER(?)', [$parameter]); + } + #[Test] #[DataProvider('falsyExpressionParametersProvider')] public function constructorWithFalsyValidParameters(mixed $falsyParameter): void @@ -318,6 +363,29 @@ public function setParameters(): void static::assertEquals([new Value('foo'), new Value('bar')], $expression->getParameters()); } + #[Test] + #[DataProvider('untypedParameterProvider')] + public function setParametersKeepsUntypedParameters( + mixed $parameter, + ArgumentInterface $expected, + ): void { + $expression = (new Expression())->setParameters([$parameter]); + + static::assertEquals([$expected], $expression->getParameters()); + } + + #[Test] + #[DataProvider('typedParameterProvider')] + public function setParametersRejectsTypedParameter(array $parameter, string $key, string $type): void + { + $expression = new Expression('UPPER(?)'); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(sprintf(InvalidArgumentException::TYPED_EXPRESSION_PARAMETER, $key, $type)); + + $expression->setParameters([$parameter]); + } + #[Test] public function setParametersWrapsArrayInValuesArgument(): void { diff --git a/test/unit/Sql/Predicate/ExpressionTest.php b/test/unit/Sql/Predicate/ExpressionTest.php index 590bffc2..06ff5c0f 100644 --- a/test/unit/Sql/Predicate/ExpressionTest.php +++ b/test/unit/Sql/Predicate/ExpressionTest.php @@ -9,6 +9,7 @@ use PhpDb\Sql\Argument\Value; use PhpDb\Sql\ArgumentInterface; use PhpDb\Sql\ArgumentType; +use PhpDb\Sql\Exception\InvalidArgumentException; use PhpDb\Sql\Exception\RuntimeException; use PhpDb\Sql\Predicate\Expression; use PhpDb\Sql\Predicate\IsNull; @@ -207,6 +208,17 @@ public function parameterIsMutable(): void static::assertEquals(ArgumentType::Value, $parameters2[4]->getType()); } + #[Test] + public function rejectsTypedParameter(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + sprintf(InvalidArgumentException::TYPED_EXPRESSION_PARAMETER, 'a', 'identifier'), + ); + + new Expression('LOWER(?) = ?', [['a' => 'identifier'], 'x']); + } + #[Test] public function retrievingWherePartsReturnsSpecificationArrayOfLiteralAndParametersAndArrayOfTypes(): void {