Skip to content
Merged
27 changes: 27 additions & 0 deletions docs/book/sql/where-having.md
Original file line number Diff line number Diff line change
Expand Up @@ -517,10 +517,37 @@ 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`), 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(
(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`. 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

### between() and notBetween()
Expand Down
156 changes: 156 additions & 0 deletions src/Sql/Predicate/CustomSpecification.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
<?php

declare(strict_types=1);

namespace PhpDb\Sql\Predicate;

use PhpDb\Sql\Argument\Values;
use PhpDb\Sql\ArgumentInterface;
use PhpDb\Sql\ArgumentType;
use PhpDb\Sql\Predicate\Exception\InvalidArgumentException;

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;

/**
* Aligns a user-supplied predicate specification with the values its arguments render
*
* 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. A specification must use one
* placeholder style throughout; 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
*
* 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, which starts at 1
*/
private const string PLACEHOLDER = '/^%(?:([1-9]\d*)\$)?s$/';

/**
* @param list<ArgumentInterface> $arguments
* @throws InvalidArgumentException When the specification contains a conversion other than
* %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
{
$placeholders = self::placeholders($arguments);
$referenced = [];
$sequential = 0;
$plain = null;
$expanded = '';

/** @var list<string> $parts */
$parts = preg_split(self::CONVERSION, $specification, flags: PREG_SPLIT_DELIM_CAPTURE);
foreach ($parts as $part => $text) {
if (0 === ($part % 2)) {
$expanded .= $text;
continue;
}

$match = [];
if (1 !== preg_match(self::PLACEHOLDER, $text, $match)) {
throw InvalidArgumentException::forSpecificationUnsupportedPlaceholder(
$specification,
$text,
strlen(implode('', array_slice($parts, offset: 0, length: $part))),
);
}

$positional = $match[1] ?? '';
$isPlain = '' === $positional;
$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);
}

$referenced[] = $index;
$expanded .= $run;
}

$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,
);
}

/**
* 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<ArgumentInterface> $arguments
* @return array<int, string>
*/
private static function placeholders(array $arguments): array
{
$placeholders = [];
$position = 1;
foreach ($arguments as $index => $argument) {
$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 $placeholders;
}
}
42 changes: 42 additions & 0 deletions src/Sql/Predicate/Exception/InvalidArgumentException.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ 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 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" at offset %d; 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);
Expand Down Expand Up @@ -89,4 +97,38 @@ 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));
}

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,
int $offset,
): self {
return new self(sprintf(self::SPECIFICATION_UNSUPPORTED_PLACEHOLDER, $specification, $placeholder, $offset));
}
}
13 changes: 11 additions & 2 deletions src/Sql/Predicate/In.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
];
}

Expand Down
Loading
Loading