From ea5dbb952052067950434eda9925c98da5509df4 Mon Sep 17 00:00:00 2001 From: Simon Mundy Date: Tue, 13 Oct 2026 12:36:57 +1100 Subject: [PATCH 1/5] Render every value of an In list through a custom specification A custom In/NotIn specification refers to the value set with one placeholder, but the value set renders one value per list item. With more than one value the extra values were dropped from the SQL while still being bound, leaving orphan parameters in prepared statements. Custom specifications are now rewritten so each placeholder covers every value its argument renders (positional placeholders, an empty list as NULL), and a specification that repeats or omits an argument that binds values, or names a missing argument, throws a Predicate InvalidArgumentException. --- docs/book/sql/where-having.md | 25 +++ src/Sql/Predicate/CustomSpecification.php | 125 ++++++++++++++ .../Exception/InvalidArgumentException.php | 25 +++ src/Sql/Predicate/In.php | 13 +- .../Sql/Predicate/CustomSpecificationTest.php | 158 ++++++++++++++++++ .../InvalidArgumentExceptionTest.php | 34 ++-- test/unit/Sql/Predicate/InTest.php | 120 +++++++++++++ test/unit/Sql/Predicate/NotInTest.php | 27 +++ 8 files changed, 514 insertions(+), 13 deletions(-) create mode 100644 src/Sql/Predicate/CustomSpecification.php create mode 100644 test/unit/Sql/Predicate/CustomSpecificationTest.php diff --git a/docs/book/sql/where-having.md b/docs/book/sql/where-having.md index 31573e4f0..a7cafade8 100644 --- a/docs/book/sql/where-having.md +++ b/docs/book/sql/where-having.md @@ -517,10 +517,35 @@ class In implements PredicateInterface array|Select|ArgumentInterface $valueSet ) : static; public function getValueSet() : ?ArgumentInterface; + public function setSpecification(string $specification) : static; + public function getSpecification() : ?string; public function getExpressionData() : ExpressionData; } ``` +A custom specification refers to the identifier and the value set with one +placeholder each, plain (`%s`) or positional (`%1$s`, `%2$s`). The value set's +placeholder receives the whole list, comma-separated, with no parentheses +added; an empty list renders as `NULL`. + +```php title="Using a custom specification with In" +$where->addPredicate( + (new Predicate\In('id', [1, 2, 3]))->setSpecification('%1$s = ANY (ARRAY[%2$s])') +); +``` + +Produces: + +```sql title="SQL output for a custom In specification" +WHERE "id" = ANY (ARRAY['1', '2', '3']) +``` + +The value set must be referenced exactly once, as must an identifier that binds +a parameter (such as `Argument::value()`), so the rendered placeholders always +match the bound parameters. A specification that repeats or omits one, or +references an argument the predicate does not have, throws +`PhpDb\Sql\Predicate\Exception\InvalidArgumentException`. + ## Range Predicates ### between() and notBetween() diff --git a/src/Sql/Predicate/CustomSpecification.php b/src/Sql/Predicate/CustomSpecification.php new file mode 100644 index 000000000..24b024a60 --- /dev/null +++ b/src/Sql/Predicate/CustomSpecification.php @@ -0,0 +1,125 @@ + $arguments + * @throws InvalidArgumentException When a placeholder names a missing argument, or an + * argument that binds values is not referenced exactly once. + */ + public static function expand(string $specification, array $arguments): string + { + $offsets = self::offsets($arguments); + $referenced = []; + $sequential = 0; + $expanded = ''; + + /** @var list $parts */ + $parts = preg_split('/%%(*SKIP)(*FAIL)|(%(?:\d+\$)?s)/', $specification, flags: PREG_SPLIT_DELIM_CAPTURE); + foreach ($parts as $part => $text) { + if (0 === ($part % 2)) { + $expanded .= $text; + continue; + } + + $index = '%s' === $text ? $sequential++ : (int) substr($text, offset: 1, length: -2) - 1; + $argument = $arguments[$index] ?? throw InvalidArgumentException::forSpecificationArgumentOutOfRange( + $specification, + $index + 1, + count($arguments), + ); + + $referenced[] = $index; + $expanded .= self::placeholders($argument, $offsets[$index] ?? 1); + } + + $references = array_count_values($referenced); + foreach ($arguments as $index => $argument) { + $count = $references[$index] ?? 0; + if (1 !== $count && self::bindsValues($argument)) { + throw InvalidArgumentException::forSpecificationArgumentNotReferencedOnce( + $specification, + $index + 1, + $count, + ); + } + } + + return $expanded; + } + + /** + * Whether rendering the argument binds parameters, so repeating or omitting it would misalign them + */ + private static function bindsValues(ArgumentInterface $argument): bool + { + return ! in_array( + $argument->getType(), + [ArgumentType::Identifier, ArgumentType::Identifiers, ArgumentType::Literal], + strict: true, + ); + } + + /** + * Position of each argument's first rendered value + * + * @param list $arguments + * @return array + */ + private static function offsets(array $arguments): array + { + $offsets = []; + $position = 1; + foreach ($arguments as $index => $argument) { + $offsets[$index] = $position; + $position += $argument instanceof Values ? count($argument->getValue()) : 1; + } + + return $offsets; + } + + /** + * Positional placeholders for every value an argument renders, starting at $offset + */ + private static function placeholders(ArgumentInterface $argument, int $offset): string + { + $count = $argument instanceof Values ? count($argument->getValue()) : 1; + + return 0 === $count + ? 'NULL' + : implode(', ', array_map( + static fn(int $position): string => "%{$position}\$s", + range($offset, $offset + $count - 1), + )); + } +} diff --git a/src/Sql/Predicate/Exception/InvalidArgumentException.php b/src/Sql/Predicate/Exception/InvalidArgumentException.php index 4209eb362..100c52668 100644 --- a/src/Sql/Predicate/Exception/InvalidArgumentException.php +++ b/src/Sql/Predicate/Exception/InvalidArgumentException.php @@ -35,6 +35,10 @@ class InvalidArgumentException extends Exception\InvalidArgumentException final public const string PREDICATE_WITH_STRING_KEY = 'Using Predicate must not use string keys'; + final public const string SPECIFICATION_ARGUMENT_NOT_REFERENCED_ONCE = 'Specification "%s" must reference argument %d exactly once because it binds values, but references it %d times'; + + final public const string SPECIFICATION_ARGUMENT_OUT_OF_RANGE = 'Specification "%s" references argument %d, but only %d arguments are available'; + public static function forInvalidCombination(): self { return new self(self::INVALID_COMBINATION); @@ -89,4 +93,25 @@ public static function forPredicateWithStringKey(): self { return new self(self::PREDICATE_WITH_STRING_KEY); } + + public static function forSpecificationArgumentNotReferencedOnce( + string $specification, + int $position, + int $references, + ): self { + return new self(sprintf( + self::SPECIFICATION_ARGUMENT_NOT_REFERENCED_ONCE, + $specification, + $position, + $references, + )); + } + + public static function forSpecificationArgumentOutOfRange( + string $specification, + int $position, + int $available, + ): self { + return new self(sprintf(self::SPECIFICATION_ARGUMENT_OUT_OF_RANGE, $specification, $position, $available)); + } } diff --git a/src/Sql/Predicate/In.php b/src/Sql/Predicate/In.php index 8e4c898bb..317d1685e 100644 --- a/src/Sql/Predicate/In.php +++ b/src/Sql/Predicate/In.php @@ -52,12 +52,21 @@ public function getExpressionData(): array throw InvalidArgumentException::forMissingValueSet(); } + $values = [$this->identifier, $this->valueSet]; + + if (null !== $this->specification) { + return [ + 'spec' => CustomSpecification::expand($this->specification, $values), + 'values' => $values, + ]; + } + $identifierSpec = $this->identifier->getSpecification(); $valueSetSpec = $this->valueSet->getSpecification(); return [ - 'spec' => $this->specification ?? "{$identifierSpec} {$this->operator} {$valueSetSpec}", - 'values' => [$this->identifier, $this->valueSet], + 'spec' => "{$identifierSpec} {$this->operator} {$valueSetSpec}", + 'values' => $values, ]; } diff --git a/test/unit/Sql/Predicate/CustomSpecificationTest.php b/test/unit/Sql/Predicate/CustomSpecificationTest.php new file mode 100644 index 000000000..4dfec38ee --- /dev/null +++ b/test/unit/Sql/Predicate/CustomSpecificationTest.php @@ -0,0 +1,158 @@ +, string}> */ + public static function expansionProvider(): array + { + return [ + 'one value, positional placeholders' => [ + '%1$s = ANY (ARRAY[%2$s])', + [Argument::identifier('id'), Argument::values([1])], + '%1$s = ANY (ARRAY[%2$s])', + ], + 'two values, positional placeholders' => [ + '%1$s = ANY (ARRAY[%2$s])', + [Argument::identifier('id'), Argument::values([1, 2])], + '%1$s = ANY (ARRAY[%2$s, %3$s])', + ], + 'three values, plain placeholders' => [ + '%s = ANY (ARRAY[%s])', + [Argument::identifier('id'), Argument::values([1, 2, 3])], + '%1$s = ANY (ARRAY[%2$s, %3$s, %4$s])', + ], + 'list placed before the identifier' => [ + 'ARRAY[%2$s] @> ARRAY[%1$s]', + [Argument::identifier('id'), Argument::values([1, 2])], + 'ARRAY[%2$s, %3$s] @> ARRAY[%1$s]', + ], + 'identifier referenced twice' => [ + '(%1$s IS NULL OR %1$s IN (%2$s))', + [Argument::identifier('id'), Argument::values([1, 2])], + '(%1$s IS NULL OR %1$s IN (%2$s, %3$s))', + ], + 'escaped percent sign kept' => [ + "%1\$s IN (%2\$s) AND 'a%%' <> ''", + [Argument::identifier('id'), Argument::values([1, 2])], + "%1\$s IN (%2\$s, %3\$s) AND 'a%%' <> ''", + ], + 'escaped percent before an s kept' => [ + "%1\$s IN (%2\$s) AND 'a%%s' <> ''", + [Argument::identifier('id'), Argument::values([1, 2])], + "%1\$s IN (%2\$s, %3\$s) AND 'a%%s' <> ''", + ], + 'empty list' => [ + '%1$s = ANY (ARRAY[%2$s])', + [Argument::identifier('id'), Argument::values([])], + '%1$s = ANY (ARRAY[NULL])', + ], + 'sub-select value set' => [ + '%1$s = ANY %2$s', + [Argument::identifier('id'), Argument::select(new Select('u'))], + '%1$s = ANY %2$s', + ], + 'list identifier shifts the value set' => [ + 'ROW(%1$s) IN (%2$s)', + [Argument::values([1, 2]), Argument::values([3, 4])], + 'ROW(%1$s, %2$s) IN (%3$s, %4$s)', + ], + ]; + } + + /** @return array, string}> */ + public static function inconsistentSpecificationProvider(): array + { + $inList = [Argument::identifier('id'), Argument::values([1, 2])]; + + return [ + 'list referenced twice' => [ + '%1$s IN (%2$s) OR %1$s = ANY (ARRAY[%2$s])', + $inList, + sprintf( + InvalidArgumentException::SPECIFICATION_ARGUMENT_NOT_REFERENCED_ONCE, + '%1$s IN (%2$s) OR %1$s = ANY (ARRAY[%2$s])', + 2, + 2, + ), + ], + 'list never referenced' => [ + '%1$s IS NOT NULL', + $inList, + sprintf(InvalidArgumentException::SPECIFICATION_ARGUMENT_NOT_REFERENCED_ONCE, '%1$s IS NOT NULL', 2, 0), + ], + 'bound value referenced twice' => [ + '%1$s IN (%2$s) OR %1$s IS NULL', + [Argument::value('a'), Argument::values([1])], + sprintf( + InvalidArgumentException::SPECIFICATION_ARGUMENT_NOT_REFERENCED_ONCE, + '%1$s IN (%2$s) OR %1$s IS NULL', + 1, + 2, + ), + ], + 'missing argument referenced' => [ + '%1$s IN (%3$s)', + $inList, + sprintf(InvalidArgumentException::SPECIFICATION_ARGUMENT_OUT_OF_RANGE, '%1$s IN (%3$s)', 3, 2), + ], + 'too many plain placeholders' => [ + '%s IN (%s) OR %s', + $inList, + sprintf(InvalidArgumentException::SPECIFICATION_ARGUMENT_OUT_OF_RANGE, '%s IN (%s) OR %s', 3, 2), + ], + ]; + } + + /** @param list $arguments */ + #[Test] + #[DataProvider('expansionProvider')] + public function eachPlaceholderCoversEveryValueItsArgumentRenders( + string $specification, + array $arguments, + string $expected, + ): void { + static::assertSame($expected, CustomSpecification::expand($specification, $arguments)); + } + + /** @param list $arguments */ + #[Test] + #[DataProvider('inconsistentSpecificationProvider')] + public function specificationThatWouldMisalignParametersIsRejected( + string $specification, + array $arguments, + string $expectedMessage, + ): void { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage($expectedMessage); + + CustomSpecification::expand($specification, $arguments); + } + + #[Test] + public function unboundArgumentsMayBeOmitted(): void + { + static::assertSame( + 'EXISTS (%2$s)', + CustomSpecification::expand('EXISTS (%2$s)', [Argument::literal('1'), Argument::values([1])]), + ); + } +} diff --git a/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php b/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php index 78a975833..aaecb87f7 100644 --- a/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php +++ b/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php @@ -26,67 +26,79 @@ #[CoversMethod(InvalidArgumentException::class, 'forMissingValueSet')] #[CoversMethod(InvalidArgumentException::class, 'forMixedCaseMagicProperty')] #[CoversMethod(InvalidArgumentException::class, 'forPredicateWithStringKey')] +#[CoversMethod(InvalidArgumentException::class, 'forSpecificationArgumentNotReferencedOnce')] +#[CoversMethod(InvalidArgumentException::class, 'forSpecificationArgumentOutOfRange')] final class InvalidArgumentExceptionTest extends TestCase { /** @return array, string}> */ public static function namedConstructorProvider(): array { return [ - 'invalid combination' => [ + 'invalid combination' => [ 'forInvalidCombination', [], InvalidArgumentException::INVALID_COMBINATION, ], - 'invalid list predicate' => [ + 'invalid list predicate' => [ 'forInvalidListPredicate', [], InvalidArgumentException::INVALID_LIST_PREDICATE, ], - 'missing identifier' => [ + 'missing identifier' => [ 'forMissingIdentifier', [], InvalidArgumentException::MISSING_IDENTIFIER, ], - 'missing left expression' => [ + 'missing left expression' => [ 'forMissingLeftExpression', [], InvalidArgumentException::MISSING_LEFT_EXPRESSION, ], - 'missing like expression' => [ + 'missing like expression' => [ 'forMissingLikeExpression', [], InvalidArgumentException::MISSING_LIKE_EXPRESSION, ], - 'missing max value' => [ + 'missing max value' => [ 'forMissingMaxValue', [], InvalidArgumentException::MISSING_MAX_VALUE, ], - 'missing min value' => [ + 'missing min value' => [ 'forMissingMinValue', [], InvalidArgumentException::MISSING_MIN_VALUE, ], - 'missing right expression' => [ + 'missing right expression' => [ 'forMissingRightExpression', [], InvalidArgumentException::MISSING_RIGHT_EXPRESSION, ], - 'missing value set' => [ + 'missing value set' => [ 'forMissingValueSet', [], InvalidArgumentException::MISSING_VALUE_SET, ], - 'mixed case magic property' => [ + 'mixed case magic property' => [ 'forMixedCaseMagicProperty', ['Or'], InvalidArgumentException::MIXED_CASE_MAGIC_PROPERTY, ], - 'predicate with string key' => [ + 'predicate with string key' => [ 'forPredicateWithStringKey', [], InvalidArgumentException::PREDICATE_WITH_STRING_KEY, ], + 'specification argument not referenced once' => [ + 'forSpecificationArgumentNotReferencedOnce', + ['%1$s IN (%2$s) OR %1$s IN (%2$s)', 2, 2], + InvalidArgumentException::SPECIFICATION_ARGUMENT_NOT_REFERENCED_ONCE, + ], + 'specification argument out of range' => [ + 'forSpecificationArgumentOutOfRange', + ['%1$s IN (%3$s)', 3, 2], + InvalidArgumentException::SPECIFICATION_ARGUMENT_OUT_OF_RANGE, + ], ]; } diff --git a/test/unit/Sql/Predicate/InTest.php b/test/unit/Sql/Predicate/InTest.php index cc9279012..8c5132ffd 100644 --- a/test/unit/Sql/Predicate/InTest.php +++ b/test/unit/Sql/Predicate/InTest.php @@ -4,6 +4,9 @@ namespace PhpDbTest\Sql\Predicate; +use PhpDb\Adapter\AdapterInterface; +use PhpDb\Adapter\Driver\DriverInterface; +use PhpDb\Adapter\StatementContainer; use PhpDb\Sql\Argument; use PhpDb\Sql\Argument\Select as ArgumentSelect; use PhpDb\Sql\Argument\Values; @@ -12,7 +15,9 @@ use PhpDb\Sql\Predicate\Exception\InvalidArgumentException; use PhpDb\Sql\Predicate\In; use PhpDb\Sql\Select; +use PhpDbTest\TestAsset\TrustingSql92Platform; use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -26,6 +31,65 @@ #[Group('unit')] final class InTest extends TestCase { + /** @return array}> */ + public static function customSpecificationPreparedProvider(): array + { + return [ + 'one value, positional placeholders' => [ + (new In('id', [1]))->setSpecification('%1$s = ANY (ARRAY[%2$s])'), + 'SELECT "t".* FROM "t" WHERE "id" = ANY (ARRAY[:where1])', + ['where1' => 1], + ], + 'two values, positional placeholders' => [ + (new In('id', [1, 2]))->setSpecification('%1$s = ANY (ARRAY[%2$s])'), + 'SELECT "t".* FROM "t" WHERE "id" = ANY (ARRAY[:where1, :where2])', + ['where1' => 1, 'where2' => 2], + ], + 'three values, plain placeholders' => [ + (new In('id', [1, 2, 3]))->setSpecification('%s = ANY (ARRAY[%s])'), + 'SELECT "t".* FROM "t" WHERE "id" = ANY (ARRAY[:where1, :where2, :where3])', + ['where1' => 1, 'where2' => 2, 'where3' => 3], + ], + 'empty list' => [ + (new In('id', []))->setSpecification('%1$s = ANY (ARRAY[%2$s])'), + 'SELECT "t".* FROM "t" WHERE "id" = ANY (ARRAY[NULL])', + [], + ], + ]; + } + + /** @return array */ + public static function customSpecificationSqlProvider(): array + { + return [ + 'one value, positional placeholders' => [ + (new In('id', [1]))->setSpecification('%1$s = ANY (ARRAY[%2$s])'), + 'SELECT "t".* FROM "t" WHERE "id" = ANY (ARRAY[\'1\'])', + ], + 'two values, positional placeholders' => [ + (new In('id', [1, 2]))->setSpecification('%1$s = ANY (ARRAY[%2$s])'), + 'SELECT "t".* FROM "t" WHERE "id" = ANY (ARRAY[\'1\', \'2\'])', + ], + 'three values, plain placeholders' => [ + (new In('id', [1, 2, 3]))->setSpecification('%s = ANY (ARRAY[%s])'), + 'SELECT "t".* FROM "t" WHERE "id" = ANY (ARRAY[\'1\', \'2\', \'3\'])', + ], + 'list placed before the identifier' => [ + (new In('id', [1, 2]))->setSpecification('ARRAY[%2$s] @> ARRAY[%1$s]'), + 'SELECT "t".* FROM "t" WHERE ARRAY[\'1\', \'2\'] @> ARRAY["id"]', + ], + 'empty list' => [ + (new In('id', []))->setSpecification('%1$s = ANY (ARRAY[%2$s])'), + 'SELECT "t".* FROM "t" WHERE "id" = ANY (ARRAY[NULL])', + ], + 'sub-select value set' => [ + (new In('id', (new Select('u'))->columns(['id'])->where(['active' => 1]))) + ->setSpecification('%1$s = ANY %2$s'), + 'SELECT "t".* FROM "t" WHERE "id" = ANY (SELECT "u"."id" AS "id" FROM "u" WHERE "active" = \'1\')', + ], + ]; + } + #[Test] public function canPassIdentifierAndEmptyValueSetToConstructor(): void { @@ -62,6 +126,47 @@ public function canPassIdentifierAndValueSetToConstructor(): void static::assertEquals(ArgumentType::Values, $valueSet->getType()); } + /** @param array $expectedParameters */ + #[Test] + #[DataProvider('customSpecificationPreparedProvider')] + public function customSpecificationBindsEveryListValueOnce( + In $in, + string $expectedSql, + array $expectedParameters, + ): void { + $statement = $this->prepare((new Select('t'))->where([$in])); + + static::assertSame( + [$expectedSql, $expectedParameters], + [$statement->getSql(), $statement->getParameterContainer()?->getNamedArray()], + ); + } + + #[Test] + public function customSpecificationBindsSubSelectParametersOnce(): void + { + $in = (new In('id', (new Select('u'))->columns(['id'])->where(['active' => 1]))) + ->setSpecification('%s = ANY %s'); + $statement = $this->prepare((new Select('t'))->where([$in])); + + static::assertSame( + [ + 'SELECT "t".* FROM "t" WHERE "id" = ANY (SELECT "u"."id" AS "id" FROM "u" WHERE "active" = :subselect1where1)', + ['subselect1where1' => 1], + ], + [$statement->getSql(), $statement->getParameterContainer()?->getNamedArray()], + ); + } + + #[Test] + #[DataProvider('customSpecificationSqlProvider')] + public function customSpecificationRendersEveryListValue(In $in, string $expectedSql): void + { + $select = (new Select('t'))->where([$in]); + + static::assertSame($expectedSql, $select->getSqlString(new TrustingSql92Platform())); + } + #[Test] public function emptyConstructorYieldsNullIdentifierAndValueSet(): void { @@ -319,4 +424,19 @@ public function valueSetIsMutable(): void static::assertEquals([3, 4, 5], $valueSet2->getValue()); static::assertEquals(ArgumentType::Values, $valueSet2->getType()); } + + private function prepare(Select $select): StatementContainer + { + $driver = $this->createStub(DriverInterface::class); + $driver->method('formatParameterName')->willReturnCallback(static fn(string $name): string => ":{$name}"); + + $adapter = $this->createStub(AdapterInterface::class); + $adapter->method('getDriver')->willReturn($driver); + $adapter->method('getPlatform')->willReturn(new TrustingSql92Platform()); + + $statement = new StatementContainer(); + $select->prepareStatement($adapter, $statement); + + return $statement; + } } diff --git a/test/unit/Sql/Predicate/NotInTest.php b/test/unit/Sql/Predicate/NotInTest.php index 645c0cc4a..a0c3050aa 100644 --- a/test/unit/Sql/Predicate/NotInTest.php +++ b/test/unit/Sql/Predicate/NotInTest.php @@ -9,11 +9,38 @@ use PhpDb\Sql\ArgumentType; use PhpDb\Sql\Predicate\NotIn; use PhpDb\Sql\Select; +use PhpDbTest\TestAsset\TrustingSql92Platform; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +#[CoversMethod(NotIn::class, 'getExpressionData')] +#[Group('unit')] final class NotInTest extends TestCase { + /** @return array, string}> */ + public static function customSpecificationProvider(): array + { + return [ + 'one value' => [[1], 'SELECT "t".* FROM "t" WHERE NOT ("id" = ANY (ARRAY[\'1\']))'], + 'two values' => [[1, 2], 'SELECT "t".* FROM "t" WHERE NOT ("id" = ANY (ARRAY[\'1\', \'2\']))'], + 'three values' => [[1, 2, 3], 'SELECT "t".* FROM "t" WHERE NOT ("id" = ANY (ARRAY[\'1\', \'2\', \'3\']))'], + ]; + } + + /** @param list $valueSet */ + #[Test] + #[DataProvider('customSpecificationProvider')] + public function customSpecificationRendersEveryListValue(array $valueSet, string $expectedSql): void + { + $notIn = (new NotIn('id', $valueSet))->setSpecification('NOT (%s = ANY (ARRAY[%s]))'); + $select = (new Select('t'))->where([$notIn]); + + static::assertSame($expectedSql, $select->getSqlString(new TrustingSql92Platform())); + } + #[Test] public function getExpressionDataWithSubselect(): void { From ad9d06a12578900e6b5d854cc40cb9a18bedbff7 Mon Sep 17 00:00:00 2001 From: Simon Mundy Date: Wed, 4 Nov 2026 13:19:37 +1100 Subject: [PATCH 2/5] Reject unsupported conversions in custom In specifications A custom specification may refer to its arguments only with %s or %N$s, and must write a literal percent sign as %%. Any other conversion, such as %d, a padded %05s or an unescaped %, previously reached vsprintf(), where it could pad an argument, consume a bound value or raise a ValueError. expand() now throws InvalidArgumentException naming the unsupported placeholder. --- docs/book/sql/where-having.md | 4 ++- src/Sql/Predicate/CustomSpecification.php | 25 ++++++++++++++--- .../Exception/InvalidArgumentException.php | 7 +++++ .../Sql/Predicate/CustomSpecificationTest.php | 27 +++++++++++++++++++ .../InvalidArgumentExceptionTest.php | 6 +++++ 5 files changed, 64 insertions(+), 5 deletions(-) diff --git a/docs/book/sql/where-having.md b/docs/book/sql/where-having.md index a7cafade8..06e43bd5f 100644 --- a/docs/book/sql/where-having.md +++ b/docs/book/sql/where-having.md @@ -544,7 +544,9 @@ The value set must be referenced exactly once, as must an identifier that binds a parameter (such as `Argument::value()`), so the rendered placeholders always match the bound parameters. A specification that repeats or omits one, or references an argument the predicate does not have, throws -`PhpDb\Sql\Predicate\Exception\InvalidArgumentException`. +`PhpDb\Sql\Predicate\Exception\InvalidArgumentException`. So does any other +`%` conversion, such as `%d` or a padded `%05s`; write a literal percent sign as +`%%`. ## Range Predicates diff --git a/src/Sql/Predicate/CustomSpecification.php b/src/Sql/Predicate/CustomSpecification.php index 24b024a60..c2a42a54e 100644 --- a/src/Sql/Predicate/CustomSpecification.php +++ b/src/Sql/Predicate/CustomSpecification.php @@ -14,6 +14,7 @@ use function count; use function implode; use function in_array; +use function preg_match; use function preg_split; use function range; use function substr; @@ -26,16 +27,28 @@ * A custom specification refers to each argument with a single placeholder, plain (%s) or * positional (%2$s), but a Values argument renders one value per list item. Each placeholder * is replaced by positional placeholders for every value its argument renders, so %2$s becomes - * %2$s, %3$s for a two-value list and NULL for an empty one. + * %2$s, %3$s for a two-value list and NULL for an empty one. Any other conversion is rejected, + * so a literal percent sign must be written as %%. * * @internal */ final class CustomSpecification { + /** + * Any vsprintf() conversion, matched the way vsprintf() reads one, leaving %% as literal text + */ + private const string CONVERSION = '/%%(*SKIP)(*FAIL)|(%(?:\d+\$)?[-+ 0]*(?:\'.)?\d*(?:\.\d+)?[a-zA-Z]?)/'; + + /** + * The conversions that may refer to an argument: plain (%s) or positional (%2$s) + */ + private const string PLACEHOLDER = '/^%(?:\d+\$)?s$/'; + /** * @param list $arguments - * @throws InvalidArgumentException When a placeholder names a missing argument, or an - * argument that binds values is not referenced exactly once. + * @throws InvalidArgumentException When the specification contains a conversion other than + * %s, %N$s or %%, a placeholder names a missing argument, or an argument that binds + * values is not referenced exactly once. */ public static function expand(string $specification, array $arguments): string { @@ -45,13 +58,17 @@ public static function expand(string $specification, array $arguments): string $expanded = ''; /** @var list $parts */ - $parts = preg_split('/%%(*SKIP)(*FAIL)|(%(?:\d+\$)?s)/', $specification, flags: PREG_SPLIT_DELIM_CAPTURE); + $parts = preg_split(self::CONVERSION, $specification, flags: PREG_SPLIT_DELIM_CAPTURE); foreach ($parts as $part => $text) { if (0 === ($part % 2)) { $expanded .= $text; continue; } + if (1 !== preg_match(self::PLACEHOLDER, $text)) { + throw InvalidArgumentException::forSpecificationUnsupportedPlaceholder($specification, $text); + } + $index = '%s' === $text ? $sequential++ : (int) substr($text, offset: 1, length: -2) - 1; $argument = $arguments[$index] ?? throw InvalidArgumentException::forSpecificationArgumentOutOfRange( $specification, diff --git a/src/Sql/Predicate/Exception/InvalidArgumentException.php b/src/Sql/Predicate/Exception/InvalidArgumentException.php index 100c52668..fd94e8e46 100644 --- a/src/Sql/Predicate/Exception/InvalidArgumentException.php +++ b/src/Sql/Predicate/Exception/InvalidArgumentException.php @@ -39,6 +39,8 @@ class InvalidArgumentException extends Exception\InvalidArgumentException final public const string SPECIFICATION_ARGUMENT_OUT_OF_RANGE = 'Specification "%s" references argument %d, but only %d arguments are available'; + final public const string SPECIFICATION_UNSUPPORTED_PLACEHOLDER = 'Specification "%s" contains unsupported placeholder "%s"; use %%s or %%N$s for an argument and %%%% for a literal percent sign'; + public static function forInvalidCombination(): self { return new self(self::INVALID_COMBINATION); @@ -114,4 +116,9 @@ public static function forSpecificationArgumentOutOfRange( ): self { return new self(sprintf(self::SPECIFICATION_ARGUMENT_OUT_OF_RANGE, $specification, $position, $available)); } + + public static function forSpecificationUnsupportedPlaceholder(string $specification, string $placeholder): self + { + return new self(sprintf(self::SPECIFICATION_UNSUPPORTED_PLACEHOLDER, $specification, $placeholder)); + } } diff --git a/test/unit/Sql/Predicate/CustomSpecificationTest.php b/test/unit/Sql/Predicate/CustomSpecificationTest.php index 4dfec38ee..e4f1624c3 100644 --- a/test/unit/Sql/Predicate/CustomSpecificationTest.php +++ b/test/unit/Sql/Predicate/CustomSpecificationTest.php @@ -122,6 +122,33 @@ public static function inconsistentSpecificationProvider(): array ]; } + /** @return array */ + public static function unsupportedPlaceholderProvider(): array + { + return [ + 'padded positional placeholder' => ['%1$05s IN (%2$s)', '%1$05s'], + 'padded plain placeholder' => ['%05s IN (%s)', '%05s'], + 'precision on a placeholder' => ['%.3s IN (%s)', '%.3s'], + 'custom padding character' => ["%'*5s IN (%s)", "%'*5s"], + 'integer conversion' => ['%s IN (%s) AND %d', '%d'], + 'positional integer conversion' => ['%1$s IN (%2$s) AND %1$d', '%1$d'], + 'unescaped percent before text' => ["%s IN (%s) AND x LIKE '50% off'", '% o'], + 'unescaped percent at the end' => ['%s IN (%s) AND 50%', '%'], + 'unsupported conversion only' => ['%s = ANY (%d)', '%d'], + ]; + } + + #[Test] + #[DataProvider('unsupportedPlaceholderProvider')] + public function conversionOtherThanSupportedPlaceholdersIsRejected(string $specification, string $placeholder): void + { + $this->expectExceptionObject( + InvalidArgumentException::forSpecificationUnsupportedPlaceholder($specification, $placeholder), + ); + + CustomSpecification::expand($specification, [Argument::identifier('id'), Argument::values([1, 2])]); + } + /** @param list $arguments */ #[Test] #[DataProvider('expansionProvider')] diff --git a/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php b/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php index aaecb87f7..3bca28406 100644 --- a/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php +++ b/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php @@ -28,6 +28,7 @@ #[CoversMethod(InvalidArgumentException::class, 'forPredicateWithStringKey')] #[CoversMethod(InvalidArgumentException::class, 'forSpecificationArgumentNotReferencedOnce')] #[CoversMethod(InvalidArgumentException::class, 'forSpecificationArgumentOutOfRange')] +#[CoversMethod(InvalidArgumentException::class, 'forSpecificationUnsupportedPlaceholder')] final class InvalidArgumentExceptionTest extends TestCase { /** @return array, string}> */ @@ -99,6 +100,11 @@ public static function namedConstructorProvider(): array ['%1$s IN (%3$s)', 3, 2], InvalidArgumentException::SPECIFICATION_ARGUMENT_OUT_OF_RANGE, ], + 'specification unsupported placeholder' => [ + 'forSpecificationUnsupportedPlaceholder', + ['%1$05s IN (%2$s)', '%1$05s'], + InvalidArgumentException::SPECIFICATION_UNSUPPORTED_PLACEHOLDER, + ], ]; } From 356d4b604515fa50e3d8d856bddb34879639ff29 Mon Sep 17 00:00:00 2001 From: Simon Mundy Date: Wed, 4 Nov 2026 13:56:34 +1100 Subject: [PATCH 3/5] Reject mixed placeholder styles in custom In specifications Capture a positional placeholder's argument number in the placeholder pattern rather than slicing it out with substr(), and require a specification to use plain (%s) or positional (%N$s) placeholders throughout. Mixing them now throws InvalidArgumentException with its own message. Adopted from the review of #247. --- docs/book/sql/where-having.md | 12 ++++---- src/Sql/Predicate/CustomSpecification.php | 28 +++++++++++++------ .../Exception/InvalidArgumentException.php | 7 +++++ .../Sql/Predicate/CustomSpecificationTest.php | 10 +++++++ .../InvalidArgumentExceptionTest.php | 6 ++++ 5 files changed, 48 insertions(+), 15 deletions(-) diff --git a/docs/book/sql/where-having.md b/docs/book/sql/where-having.md index 06e43bd5f..802fce555 100644 --- a/docs/book/sql/where-having.md +++ b/docs/book/sql/where-having.md @@ -524,9 +524,9 @@ class In implements PredicateInterface ``` A custom specification refers to the identifier and the value set with one -placeholder each, plain (`%s`) or positional (`%1$s`, `%2$s`). The value set's -placeholder receives the whole list, comma-separated, with no parentheses -added; an empty list renders as `NULL`. +placeholder each, plain (`%s`) or positional (`%1$s`, `%2$s`), using one style +throughout. The value set's placeholder receives the whole list, +comma-separated, with no parentheses added; an empty list renders as `NULL`. ```php title="Using a custom specification with In" $where->addPredicate( @@ -544,9 +544,9 @@ The value set must be referenced exactly once, as must an identifier that binds a parameter (such as `Argument::value()`), so the rendered placeholders always match the bound parameters. A specification that repeats or omits one, or references an argument the predicate does not have, throws -`PhpDb\Sql\Predicate\Exception\InvalidArgumentException`. So does any other -`%` conversion, such as `%d` or a padded `%05s`; write a literal percent sign as -`%%`. +`PhpDb\Sql\Predicate\Exception\InvalidArgumentException`. So does mixing the +two placeholder styles, or any other `%` conversion, such as `%d` or a padded +`%05s`; write a literal percent sign as `%%`. ## Range Predicates diff --git a/src/Sql/Predicate/CustomSpecification.php b/src/Sql/Predicate/CustomSpecification.php index c2a42a54e..1c51012b4 100644 --- a/src/Sql/Predicate/CustomSpecification.php +++ b/src/Sql/Predicate/CustomSpecification.php @@ -17,7 +17,6 @@ use function preg_match; use function preg_split; use function range; -use function substr; use const PREG_SPLIT_DELIM_CAPTURE; @@ -27,8 +26,9 @@ * A custom specification refers to each argument with a single placeholder, plain (%s) or * positional (%2$s), but a Values argument renders one value per list item. Each placeholder * is replaced by positional placeholders for every value its argument renders, so %2$s becomes - * %2$s, %3$s for a two-value list and NULL for an empty one. Any other conversion is rejected, - * so a literal percent sign must be written as %%. + * %2$s, %3$s for a two-value list and NULL for an empty one. A specification must use one + * placeholder style throughout; any other conversion is rejected, so a literal percent sign + * must be written as %%. * * @internal */ @@ -40,21 +40,23 @@ final class CustomSpecification private const string CONVERSION = '/%%(*SKIP)(*FAIL)|(%(?:\d+\$)?[-+ 0]*(?:\'.)?\d*(?:\.\d+)?[a-zA-Z]?)/'; /** - * The conversions that may refer to an argument: plain (%s) or positional (%2$s) + * The conversions that may refer to an argument, plain (%s) or positional (%2$s), capturing + * the argument number of a positional one */ - private const string PLACEHOLDER = '/^%(?:\d+\$)?s$/'; + private const string PLACEHOLDER = '/^%(?:(\d+)\$)?s$/'; /** * @param list $arguments * @throws InvalidArgumentException When the specification contains a conversion other than - * %s, %N$s or %%, a placeholder names a missing argument, or an argument that binds - * values is not referenced exactly once. + * %s, %N$s or %%, mixes plain and positional placeholders, a placeholder names a missing + * argument, or an argument that binds values is not referenced exactly once. */ public static function expand(string $specification, array $arguments): string { $offsets = self::offsets($arguments); $referenced = []; $sequential = 0; + $plain = null; $expanded = ''; /** @var list $parts */ @@ -65,11 +67,19 @@ public static function expand(string $specification, array $arguments): string continue; } - if (1 !== preg_match(self::PLACEHOLDER, $text)) { + $match = []; + if (1 !== preg_match(self::PLACEHOLDER, $text, $match)) { throw InvalidArgumentException::forSpecificationUnsupportedPlaceholder($specification, $text); } - $index = '%s' === $text ? $sequential++ : (int) substr($text, offset: 1, length: -2) - 1; + $positional = $match[1] ?? ''; + $isPlain = '' === $positional; + $plain ??= $isPlain; + if ($plain !== $isPlain) { + throw InvalidArgumentException::forSpecificationMixedPlaceholderStyles($specification); + } + + $index = $isPlain ? $sequential++ : (int) $positional - 1; $argument = $arguments[$index] ?? throw InvalidArgumentException::forSpecificationArgumentOutOfRange( $specification, $index + 1, diff --git a/src/Sql/Predicate/Exception/InvalidArgumentException.php b/src/Sql/Predicate/Exception/InvalidArgumentException.php index fd94e8e46..51aa2457f 100644 --- a/src/Sql/Predicate/Exception/InvalidArgumentException.php +++ b/src/Sql/Predicate/Exception/InvalidArgumentException.php @@ -39,6 +39,8 @@ class InvalidArgumentException extends Exception\InvalidArgumentException final public const string SPECIFICATION_ARGUMENT_OUT_OF_RANGE = 'Specification "%s" references argument %d, but only %d arguments are available'; + final public const string SPECIFICATION_MIXED_PLACEHOLDER_STYLES = 'Specification "%s" mixes plain (%%s) and positional (%%N$s) placeholders; use one style throughout'; + final public const string SPECIFICATION_UNSUPPORTED_PLACEHOLDER = 'Specification "%s" contains unsupported placeholder "%s"; use %%s or %%N$s for an argument and %%%% for a literal percent sign'; public static function forInvalidCombination(): self @@ -117,6 +119,11 @@ public static function forSpecificationArgumentOutOfRange( return new self(sprintf(self::SPECIFICATION_ARGUMENT_OUT_OF_RANGE, $specification, $position, $available)); } + public static function forSpecificationMixedPlaceholderStyles(string $specification): self + { + return new self(sprintf(self::SPECIFICATION_MIXED_PLACEHOLDER_STYLES, $specification)); + } + public static function forSpecificationUnsupportedPlaceholder(string $specification, string $placeholder): self { return new self(sprintf(self::SPECIFICATION_UNSUPPORTED_PLACEHOLDER, $specification, $placeholder)); diff --git a/test/unit/Sql/Predicate/CustomSpecificationTest.php b/test/unit/Sql/Predicate/CustomSpecificationTest.php index e4f1624c3..ae1c83bd6 100644 --- a/test/unit/Sql/Predicate/CustomSpecificationTest.php +++ b/test/unit/Sql/Predicate/CustomSpecificationTest.php @@ -119,6 +119,16 @@ public static function inconsistentSpecificationProvider(): array $inList, sprintf(InvalidArgumentException::SPECIFICATION_ARGUMENT_OUT_OF_RANGE, '%s IN (%s) OR %s', 3, 2), ], + 'positional then plain' => [ + '%2$s IN (%s)', + $inList, + sprintf(InvalidArgumentException::SPECIFICATION_MIXED_PLACEHOLDER_STYLES, '%2$s IN (%s)'), + ], + 'plain then positional' => [ + '%s IN (%2$s)', + $inList, + sprintf(InvalidArgumentException::SPECIFICATION_MIXED_PLACEHOLDER_STYLES, '%s IN (%2$s)'), + ], ]; } diff --git a/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php b/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php index 3bca28406..eea8daef0 100644 --- a/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php +++ b/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php @@ -28,6 +28,7 @@ #[CoversMethod(InvalidArgumentException::class, 'forPredicateWithStringKey')] #[CoversMethod(InvalidArgumentException::class, 'forSpecificationArgumentNotReferencedOnce')] #[CoversMethod(InvalidArgumentException::class, 'forSpecificationArgumentOutOfRange')] +#[CoversMethod(InvalidArgumentException::class, 'forSpecificationMixedPlaceholderStyles')] #[CoversMethod(InvalidArgumentException::class, 'forSpecificationUnsupportedPlaceholder')] final class InvalidArgumentExceptionTest extends TestCase { @@ -100,6 +101,11 @@ public static function namedConstructorProvider(): array ['%1$s IN (%3$s)', 3, 2], InvalidArgumentException::SPECIFICATION_ARGUMENT_OUT_OF_RANGE, ], + 'specification mixed placeholder styles' => [ + 'forSpecificationMixedPlaceholderStyles', + ['%2$s IN (%s)'], + InvalidArgumentException::SPECIFICATION_MIXED_PLACEHOLDER_STYLES, + ], 'specification unsupported placeholder' => [ 'forSpecificationUnsupportedPlaceholder', ['%1$05s IN (%2$s)', '%1$05s'], From 9a6c608a360834e3982ba75e907eb334681ae119 Mon Sep 17 00:00:00 2001 From: Simon Mundy Date: Wed, 4 Nov 2026 14:02:43 +1100 Subject: [PATCH 4/5] Build each argument's placeholders in one pass Merge offsets() and placeholders() into a single map of each argument's positional placeholders, keyed by argument index. expand() looks the placeholder up directly, which drops the unreachable offset fallback and brings the class back under Mago's cyclomatic complexity threshold. --- src/Sql/Predicate/CustomSpecification.php | 59 ++++++++++------------- 1 file changed, 26 insertions(+), 33 deletions(-) diff --git a/src/Sql/Predicate/CustomSpecification.php b/src/Sql/Predicate/CustomSpecification.php index 1c51012b4..57bbe9ca6 100644 --- a/src/Sql/Predicate/CustomSpecification.php +++ b/src/Sql/Predicate/CustomSpecification.php @@ -53,11 +53,11 @@ final class CustomSpecification */ public static function expand(string $specification, array $arguments): string { - $offsets = self::offsets($arguments); - $referenced = []; - $sequential = 0; - $plain = null; - $expanded = ''; + $placeholders = self::placeholders($arguments); + $referenced = []; + $sequential = 0; + $plain = null; + $expanded = ''; /** @var list $parts */ $parts = preg_split(self::CONVERSION, $specification, flags: PREG_SPLIT_DELIM_CAPTURE); @@ -79,15 +79,13 @@ public static function expand(string $specification, array $arguments): string throw InvalidArgumentException::forSpecificationMixedPlaceholderStyles($specification); } - $index = $isPlain ? $sequential++ : (int) $positional - 1; - $argument = $arguments[$index] ?? throw InvalidArgumentException::forSpecificationArgumentOutOfRange( + $index = $isPlain ? $sequential++ : (int) $positional - 1; + $referenced[] = $index; + $expanded .= $placeholders[$index] ?? throw InvalidArgumentException::forSpecificationArgumentOutOfRange( $specification, $index + 1, count($arguments), ); - - $referenced[] = $index; - $expanded .= self::placeholders($argument, $offsets[$index] ?? 1); } $references = array_count_values($referenced); @@ -118,35 +116,30 @@ private static function bindsValues(ArgumentInterface $argument): bool } /** - * Position of each argument's first rendered value + * Positional placeholders for every value each argument renders, keyed by argument index + * + * An argument's placeholders continue the sequence where the previous argument's ended, and + * an empty list renders as NULL. * * @param list $arguments - * @return array + * @return array */ - private static function offsets(array $arguments): array + private static function placeholders(array $arguments): array { - $offsets = []; - $position = 1; + $placeholders = []; + $position = 1; foreach ($arguments as $index => $argument) { - $offsets[$index] = $position; - $position += $argument instanceof Values ? count($argument->getValue()) : 1; + $count = $argument instanceof Values ? count($argument->getValue()) : 1; + + $placeholders[$index] = 0 === $count + ? 'NULL' + : implode(', ', array_map( + static fn(int $offset): string => "%{$offset}\$s", + range($position, $position + $count - 1), + )); + $position += $count; } - return $offsets; - } - - /** - * Positional placeholders for every value an argument renders, starting at $offset - */ - private static function placeholders(ArgumentInterface $argument, int $offset): string - { - $count = $argument instanceof Values ? count($argument->getValue()) : 1; - - return 0 === $count - ? 'NULL' - : implode(', ', array_map( - static fn(int $position): string => "%{$position}\$s", - range($offset, $offset + $count - 1), - )); + return $placeholders; } } From 79b6d16a88c2198a5d32097ec2d199ba6b420f9a Mon Sep 17 00:00:00 2001 From: Simon Mundy Date: Wed, 4 Nov 2026 14:10:19 +1100 Subject: [PATCH 5/5] Address review feedback on custom In specifications - Reject %0$s as an unsupported placeholder, since argument numbers start at 1. - Report a missing argument before mixed placeholder styles, so a typo in an argument number gets the more actionable message. - Include the offset of an unsupported placeholder in its message. - Reword the out-of-range message so it no longer needs a plural. - Document that the conversion pattern must keep a single capturing group, which the preg_split() parity relies on. - Cover a specification with no placeholders. --- src/Sql/Predicate/CustomSpecification.php | 31 +++++++---- .../Exception/InvalidArgumentException.php | 13 +++-- .../Sql/Predicate/CustomSpecificationTest.php | 54 ++++++++++++------- .../InvalidArgumentExceptionTest.php | 2 +- 4 files changed, 64 insertions(+), 36 deletions(-) diff --git a/src/Sql/Predicate/CustomSpecification.php b/src/Sql/Predicate/CustomSpecification.php index 57bbe9ca6..305e7d36d 100644 --- a/src/Sql/Predicate/CustomSpecification.php +++ b/src/Sql/Predicate/CustomSpecification.php @@ -11,12 +11,14 @@ use function array_count_values; use function array_map; +use function array_slice; use function count; use function implode; use function in_array; use function preg_match; use function preg_split; use function range; +use function strlen; use const PREG_SPLIT_DELIM_CAPTURE; @@ -36,14 +38,17 @@ final class CustomSpecification { /** * Any vsprintf() conversion, matched the way vsprintf() reads one, leaving %% as literal text + * + * The pattern must keep exactly one capturing group: expand() relies on preg_split() placing + * literal text at even indexes and each captured conversion at odd ones. */ private const string CONVERSION = '/%%(*SKIP)(*FAIL)|(%(?:\d+\$)?[-+ 0]*(?:\'.)?\d*(?:\.\d+)?[a-zA-Z]?)/'; /** * The conversions that may refer to an argument, plain (%s) or positional (%2$s), capturing - * the argument number of a positional one + * the argument number of a positional one, which starts at 1 */ - private const string PLACEHOLDER = '/^%(?:(\d+)\$)?s$/'; + private const string PLACEHOLDER = '/^%(?:([1-9]\d*)\$)?s$/'; /** * @param list $arguments @@ -69,23 +74,29 @@ public static function expand(string $specification, array $arguments): string $match = []; if (1 !== preg_match(self::PLACEHOLDER, $text, $match)) { - throw InvalidArgumentException::forSpecificationUnsupportedPlaceholder($specification, $text); + throw InvalidArgumentException::forSpecificationUnsupportedPlaceholder( + $specification, + $text, + strlen(implode('', array_slice($parts, offset: 0, length: $part))), + ); } $positional = $match[1] ?? ''; $isPlain = '' === $positional; - $plain ??= $isPlain; + $index = $isPlain ? $sequential++ : (int) $positional - 1; + $run = $placeholders[$index] ?? throw InvalidArgumentException::forSpecificationArgumentOutOfRange( + $specification, + $index + 1, + count($arguments), + ); + + $plain ??= $isPlain; if ($plain !== $isPlain) { throw InvalidArgumentException::forSpecificationMixedPlaceholderStyles($specification); } - $index = $isPlain ? $sequential++ : (int) $positional - 1; $referenced[] = $index; - $expanded .= $placeholders[$index] ?? throw InvalidArgumentException::forSpecificationArgumentOutOfRange( - $specification, - $index + 1, - count($arguments), - ); + $expanded .= $run; } $references = array_count_values($referenced); diff --git a/src/Sql/Predicate/Exception/InvalidArgumentException.php b/src/Sql/Predicate/Exception/InvalidArgumentException.php index 51aa2457f..0835d4898 100644 --- a/src/Sql/Predicate/Exception/InvalidArgumentException.php +++ b/src/Sql/Predicate/Exception/InvalidArgumentException.php @@ -37,11 +37,11 @@ class InvalidArgumentException extends Exception\InvalidArgumentException final public const string SPECIFICATION_ARGUMENT_NOT_REFERENCED_ONCE = 'Specification "%s" must reference argument %d exactly once because it binds values, but references it %d times'; - final public const string SPECIFICATION_ARGUMENT_OUT_OF_RANGE = 'Specification "%s" references argument %d, but only %d arguments are available'; + final public const string SPECIFICATION_ARGUMENT_OUT_OF_RANGE = 'Specification "%s" references argument %d, but the highest argument number is %d'; final public const string SPECIFICATION_MIXED_PLACEHOLDER_STYLES = 'Specification "%s" mixes plain (%%s) and positional (%%N$s) placeholders; use one style throughout'; - final public const string SPECIFICATION_UNSUPPORTED_PLACEHOLDER = 'Specification "%s" contains unsupported placeholder "%s"; use %%s or %%N$s for an argument and %%%% for a literal percent sign'; + final public const string SPECIFICATION_UNSUPPORTED_PLACEHOLDER = 'Specification "%s" contains unsupported placeholder "%s" at offset %d; use %%s or %%N$s for an argument and %%%% for a literal percent sign'; public static function forInvalidCombination(): self { @@ -124,8 +124,11 @@ public static function forSpecificationMixedPlaceholderStyles(string $specificat return new self(sprintf(self::SPECIFICATION_MIXED_PLACEHOLDER_STYLES, $specification)); } - public static function forSpecificationUnsupportedPlaceholder(string $specification, string $placeholder): self - { - return new self(sprintf(self::SPECIFICATION_UNSUPPORTED_PLACEHOLDER, $specification, $placeholder)); + public static function forSpecificationUnsupportedPlaceholder( + string $specification, + string $placeholder, + int $offset, + ): self { + return new self(sprintf(self::SPECIFICATION_UNSUPPORTED_PLACEHOLDER, $specification, $placeholder, $offset)); } } diff --git a/test/unit/Sql/Predicate/CustomSpecificationTest.php b/test/unit/Sql/Predicate/CustomSpecificationTest.php index ae1c83bd6..77483e901 100644 --- a/test/unit/Sql/Predicate/CustomSpecificationTest.php +++ b/test/unit/Sql/Predicate/CustomSpecificationTest.php @@ -50,6 +50,11 @@ public static function expansionProvider(): array [Argument::identifier('id'), Argument::values([1, 2])], '(%1$s IS NULL OR %1$s IN (%2$s, %3$s))', ], + 'no placeholders' => [ + 'TRUE', + [Argument::identifier('id')], + 'TRUE', + ], 'escaped percent sign kept' => [ "%1\$s IN (%2\$s) AND 'a%%' <> ''", [Argument::identifier('id'), Argument::values([1, 2])], @@ -84,7 +89,7 @@ public static function inconsistentSpecificationProvider(): array $inList = [Argument::identifier('id'), Argument::values([1, 2])]; return [ - 'list referenced twice' => [ + 'list referenced twice' => [ '%1$s IN (%2$s) OR %1$s = ANY (ARRAY[%2$s])', $inList, sprintf( @@ -94,12 +99,12 @@ public static function inconsistentSpecificationProvider(): array 2, ), ], - 'list never referenced' => [ + 'list never referenced' => [ '%1$s IS NOT NULL', $inList, sprintf(InvalidArgumentException::SPECIFICATION_ARGUMENT_NOT_REFERENCED_ONCE, '%1$s IS NOT NULL', 2, 0), ], - 'bound value referenced twice' => [ + 'bound value referenced twice' => [ '%1$s IN (%2$s) OR %1$s IS NULL', [Argument::value('a'), Argument::values([1])], sprintf( @@ -109,22 +114,27 @@ public static function inconsistentSpecificationProvider(): array 2, ), ], - 'missing argument referenced' => [ + 'missing argument referenced' => [ '%1$s IN (%3$s)', $inList, sprintf(InvalidArgumentException::SPECIFICATION_ARGUMENT_OUT_OF_RANGE, '%1$s IN (%3$s)', 3, 2), ], - 'too many plain placeholders' => [ + 'too many plain placeholders' => [ '%s IN (%s) OR %s', $inList, sprintf(InvalidArgumentException::SPECIFICATION_ARGUMENT_OUT_OF_RANGE, '%s IN (%s) OR %s', 3, 2), ], - 'positional then plain' => [ + 'missing argument before mixed styles' => [ + '%s IN (%3$s)', + $inList, + sprintf(InvalidArgumentException::SPECIFICATION_ARGUMENT_OUT_OF_RANGE, '%s IN (%3$s)', 3, 2), + ], + 'positional then plain' => [ '%2$s IN (%s)', $inList, sprintf(InvalidArgumentException::SPECIFICATION_MIXED_PLACEHOLDER_STYLES, '%2$s IN (%s)'), ], - 'plain then positional' => [ + 'plain then positional' => [ '%s IN (%2$s)', $inList, sprintf(InvalidArgumentException::SPECIFICATION_MIXED_PLACEHOLDER_STYLES, '%s IN (%2$s)'), @@ -132,28 +142,32 @@ public static function inconsistentSpecificationProvider(): array ]; } - /** @return array */ + /** @return array */ public static function unsupportedPlaceholderProvider(): array { return [ - 'padded positional placeholder' => ['%1$05s IN (%2$s)', '%1$05s'], - 'padded plain placeholder' => ['%05s IN (%s)', '%05s'], - 'precision on a placeholder' => ['%.3s IN (%s)', '%.3s'], - 'custom padding character' => ["%'*5s IN (%s)", "%'*5s"], - 'integer conversion' => ['%s IN (%s) AND %d', '%d'], - 'positional integer conversion' => ['%1$s IN (%2$s) AND %1$d', '%1$d'], - 'unescaped percent before text' => ["%s IN (%s) AND x LIKE '50% off'", '% o'], - 'unescaped percent at the end' => ['%s IN (%s) AND 50%', '%'], - 'unsupported conversion only' => ['%s = ANY (%d)', '%d'], + 'padded positional placeholder' => ['%1$s IN (%2$05s)', '%2$05s', 9], + 'padded plain placeholder' => ['%05s IN (%s)', '%05s', 0], + 'precision on a placeholder' => ['%.3s IN (%s)', '%.3s', 0], + 'custom padding character' => ["%'*5s IN (%s)", "%'*5s", 0], + 'argument number zero' => ['%0$s IN (%2$s)', '%0$s', 0], + 'integer conversion' => ['%s IN (%s) AND %d', '%d', 15], + 'positional integer conversion' => ['%1$s IN (%2$s) AND %1$d', '%1$d', 19], + 'unescaped percent before text' => ["%s IN (%s) AND x LIKE '50% off'", '% o', 25], + 'unescaped percent at the end' => ['%s IN (%s) AND 50%', '%', 17], + 'unsupported conversion only' => ['%s = ANY (%d)', '%d', 10], ]; } #[Test] #[DataProvider('unsupportedPlaceholderProvider')] - public function conversionOtherThanSupportedPlaceholdersIsRejected(string $specification, string $placeholder): void - { + public function conversionOtherThanSupportedPlaceholdersIsRejected( + string $specification, + string $placeholder, + int $offset, + ): void { $this->expectExceptionObject( - InvalidArgumentException::forSpecificationUnsupportedPlaceholder($specification, $placeholder), + InvalidArgumentException::forSpecificationUnsupportedPlaceholder($specification, $placeholder, $offset), ); CustomSpecification::expand($specification, [Argument::identifier('id'), Argument::values([1, 2])]); diff --git a/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php b/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php index eea8daef0..2694a47f9 100644 --- a/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php +++ b/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php @@ -108,7 +108,7 @@ public static function namedConstructorProvider(): array ], 'specification unsupported placeholder' => [ 'forSpecificationUnsupportedPlaceholder', - ['%1$05s IN (%2$s)', '%1$05s'], + ['%1$05s IN (%2$s)', '%1$05s', 0], InvalidArgumentException::SPECIFICATION_UNSUPPORTED_PLACEHOLDER, ], ];