Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/Sql/Exception/InvalidArgumentException.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 (?)';
Expand Down Expand Up @@ -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));
Expand Down
39 changes: 38 additions & 1 deletion src/Sql/Expression.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<bool|string|float|int|null>|ExpressionInterface|ArgumentInterface
*/
class Expression extends AbstractExpression
Expand All @@ -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<ArgumentInterface> */
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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<bool|string|float|int|null> $parameter
* @return list<bool|string|float|int|null>
* @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;
}
}
6 changes: 6 additions & 0 deletions test/unit/Sql/Exception/InvalidArgumentExceptionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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')]
Expand Down Expand Up @@ -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 ?'],
Expand Down
68 changes: 68 additions & 0 deletions test/unit/Sql/ExpressionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -65,6 +68,21 @@ public static function falsyExpressionParametersProvider(): array
];
}

/** @return array<string, array{array<array-key, mixed>, 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<string, array{string, list<mixed>}> */
public static function unenclosedArrayParameterProvider(): array
{
Expand All @@ -78,6 +96,33 @@ public static function unenclosedArrayParameterProvider(): array
];
}

/** @return array<string, array{mixed, ArgumentInterface}> */
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
Expand Down Expand Up @@ -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
{
Expand Down
12 changes: 12 additions & 0 deletions test/unit/Sql/Predicate/ExpressionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
{
Expand Down
Loading