| 1 |
<?php |
| 2 |
|
| 3 |
namespace Wikimedia\Rdbms; |
| 4 |
|
| 5 |
use InvalidArgumentException; |
| 6 |
use Wikimedia\Rdbms\Database\DbQuoter; |
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
class LikeValue { |
| 15 |
|
| 16 |
private array $values = []; |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
public function __construct( $value, ...$values ) { |
| 23 |
if ( !is_string( $value ) && !( $value instanceof LikeMatch ) ) { |
| 24 |
$type = get_debug_type( $value ); |
| 25 |
throw new InvalidArgumentException( "\$value must be string or LikeMatch, got $type" ); |
| 26 |
} |
| 27 |
$this->values = [ $value ]; |
| 28 |
|
| 29 |
foreach ( $values as $value ) { |
| 30 |
if ( !is_string( $value ) && !( $value instanceof LikeMatch ) ) { |
| 31 |
$type = get_debug_type( $value ); |
| 32 |
throw new InvalidArgumentException( "\$value must be string or LikeMatch, got $type" ); |
| 33 |
} |
| 34 |
$this->values[] = $value; |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
public function toSql( DbQuoter $dbQuoter ): string { |
| 43 |
$s = ''; |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
$escapeChar = '`'; |
| 50 |
|
| 51 |
foreach ( $this->values as $value ) { |
| 52 |
if ( $value instanceof LikeMatch ) { |
| 53 |
$s .= $value->toString(); |
| 54 |
} else { |
| 55 |
$s .= $this->escapeLikeInternal( $value, $escapeChar ); |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
return $dbQuoter->addQuotes( $s ) . ' ESCAPE ' . $dbQuoter->addQuotes( $escapeChar ); |
| 60 |
} |
| 61 |
|
| 62 |
private function escapeLikeInternal( $s, $escapeChar = '`' ) { |
| 63 |
return str_replace( |
| 64 |
[ $escapeChar, '%', '_' ], |
| 65 |
[ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ], |
| 66 |
$s |
| 67 |
); |
| 68 |
} |
| 69 |
} |