Skip to content
Closed
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
71 changes: 71 additions & 0 deletions src/Sql/Predicate/ArgumentPlaceholders.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

declare(strict_types=1);

namespace PhpDb\Sql\Predicate;

use PhpDb\Sql\Argument\Values;
use PhpDb\Sql\ArgumentInterface;
use PhpDb\Sql\ArgumentType;

use function array_map;
use function count;
use function implode;
use function in_array;
use function range;

/**
* Where each argument's rendered values land in a positional placeholder sequence
*
* A Values argument renders one value per list item, so it occupies a run of positions rather
* than a single one. Every other argument occupies exactly one position.
*
* @internal
*/
final class ArgumentPlaceholders
{
/**
* Whether rendering the argument binds parameters, so repeating or omitting it would misalign them
*/
public static function bindsValues(ArgumentInterface $argument): bool
{
return ! in_array(
$argument->getType(),
[ArgumentType::Identifier, ArgumentType::Identifiers, ArgumentType::Literal],
strict: true,
);
}

/**
* Placeholder text for every value each argument renders, keyed by argument index
*
* @param list<ArgumentInterface> $arguments
* @return array<int, string>
*/
public static function runs(array $arguments): array
{
$runs = [];
$position = 1;
foreach ($arguments as $index => $argument) {
$count = $argument instanceof Values ? count($argument->getValue()) : 1;

$runs[$index] = self::run($position, $count);
$position += $count;
}

return $runs;
}

/**
* Positional placeholders for $count values, starting at $position
*/
private static function run(int $position, int $count): string
{
return 0 === $count
? 'NULL'
: implode(', ', array_map(
static fn(int $offset): string => "%{$offset}\$s",
range($position, $position + $count - 1),
));
}
}
180 changes: 112 additions & 68 deletions src/Sql/Predicate/CustomSpecification.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,122 +4,166 @@

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 count;
use function implode;
use function in_array;
use function preg_split;
use function range;
use function substr;

use const PREG_SPLIT_DELIM_CAPTURE;
use function preg_match;
use function preg_replace;
use function preg_replace_callback;
use function str_contains;
use function str_replace;

/**
* 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.
* positional (%2$s). Each placeholder is replaced by the positional placeholders for every value
* its argument renders, which ArgumentPlaceholders maps.
*
* Only the string conversion is supported. Width, precision, sign, padding and alignment
* modifiers are accepted but ignored, because the value they would format is a placeholder name
* rather than a value. A literal percent must be written as %%, which is left in place for the
* caller to unescape exactly once.
*
* @internal
*/
final class CustomSpecification
{
/**
* A placeholder in plain (%s) or positional (%2$s) form, with any sprintf modifiers
*
* Escaped percents are skipped, so they never match and are therefore never rewritten.
*/
private const string PLACEHOLDER = '/%%(*SKIP)(*FAIL)|%(?:(\d+)\$)?[-+ 0\']*\d*(?:\.\d+)?([a-zA-Z])/';

/**
* A positional placeholder, and any placeholder that is not positional
*
* Escaped percents are skipped, so they never count as either style.
*/
private const string POSITIONAL_PLACEHOLDER = '/%%(*SKIP)(*FAIL)|%\d+\$/';
private const string PLAIN_PLACEHOLDER = '/%%(*SKIP)(*FAIL)|%(?!\d+\$)/';

/**
* @param list<ArgumentInterface> $arguments
* @throws InvalidArgumentException When a placeholder names a missing argument, or an
* argument that binds values is not referenced exactly once.
* @throws InvalidArgumentException When a placeholder names a missing argument, an argument
* that binds values is not referenced exactly once, a conversion other than the string
* conversion is used, plain and positional placeholders are mixed, or a percent sign is
* not escaped.
*/
public static function expand(string $specification, array $arguments): string
{
$offsets = self::offsets($arguments);
self::assertPlaceholdersAreWellFormed($specification);

$runs = ArgumentPlaceholders::runs($arguments);
$referenced = [];
$sequential = 0;
$expanded = '';

/** @var list<string> $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),
$expanded = preg_replace_callback(
self::PLACEHOLDER,
static function (array $match) use ($specification, $runs, &$referenced, &$sequential): string {
[$placeholders, $index] = self::expandPlaceholder(
match: $match,
specification: $specification,
runs: $runs,
sequential: $sequential,
);

$referenced[] = $index;
$expanded .= self::placeholders($argument, $offsets[$index] ?? 1);
}
$referenced[] = $index;

return $placeholders;
},
$specification,
);

self::assertBoundArgumentsReferencedOnce($specification, $arguments, $referenced);

return $expanded ?? '';
}

/**
* Reject a specification that does not reference every bound argument exactly once
*
* @param list<ArgumentInterface> $arguments
* @param list<int> $referenced
*/
private static function assertBoundArgumentsReferencedOnce(
string $specification,
array $arguments,
array $referenced,
): void {
$references = array_count_values($referenced);
foreach ($arguments as $index => $argument) {
$count = $references[$index] ?? 0;
if (1 !== $count && self::bindsValues($argument)) {
if (1 !== $count && ArgumentPlaceholders::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
* Reject a specification whose placeholders and percent signs cannot be expanded
*/
private static function bindsValues(ArgumentInterface $argument): bool
private static function assertPlaceholdersAreWellFormed(string $specification): void
{
return ! in_array(
$argument->getType(),
[ArgumentType::Identifier, ArgumentType::Identifiers, ArgumentType::Literal],
strict: true,
$literals = preg_replace(
pattern: self::PLACEHOLDER,
replacement: '',
subject: $specification,
);
}

/**
* Position of each argument's first rendered value
*
* @param list<ArgumentInterface> $arguments
* @return array<int, int>
*/
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;
if (str_contains(str_replace(
search: '%%',
replace: '',
subject: (string) $literals,
), '%')) {
throw InvalidArgumentException::forSpecificationUnsupportedConversion($specification, '%');
}

return $offsets;
$positional = preg_match(self::POSITIONAL_PLACEHOLDER, $specification);
$plain = preg_match(self::PLAIN_PLACEHOLDER, $specification);

if (1 === $positional && 1 === $plain) {
throw InvalidArgumentException::forSpecificationMixedPlaceholderStyles($specification);
}
}

/**
* Positional placeholders for every value an argument renders, starting at $offset
* Placeholders for one match, and the index of the argument it references
*
* @param array<int|string, string> $match
* @param array<int, string> $runs
* @return array{string, int}
*/
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),
));
private static function expandPlaceholder(
array $match,
string $specification,
array $runs,
int &$sequential,
): array {
if ('s' !== ($match[2] ?? '')) {
throw InvalidArgumentException::forSpecificationUnsupportedConversion(
$specification,
$match[0] ?? '',
);
}

$positional = $match[1] ?? '';
$index = '' === $positional ? $sequential++ : (int) $positional - 1;

return [
$runs[$index] ?? throw InvalidArgumentException::forSpecificationArgumentOutOfRange(
$specification,
$index + 1,
count($runs),
),
$index,
];
}
}
16 changes: 16 additions & 0 deletions src/Sql/Predicate/Exception/InvalidArgumentException.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ 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_CONVERSION = 'Specification "%s" contains the unsupported conversion "%s"; only %%s and %%N$s placeholders are supported and a literal percent must be escaped as %%%%';

public static function forInvalidCombination(): self
{
return new self(self::INVALID_COMBINATION);
Expand Down Expand Up @@ -114,4 +118,16 @@ public static function forSpecificationArgumentOutOfRange(
): 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 forSpecificationUnsupportedConversion(
string $specification,
string $conversion,
): self {
return new self(sprintf(self::SPECIFICATION_UNSUPPORTED_CONVERSION, $specification, $conversion));
}
}
Loading
Loading