MediaWiki master
LikeValue.php
Go to the documentation of this file.
1<?php
2
3namespace Wikimedia\Rdbms;
4
5use InvalidArgumentException;
7
14class LikeValue {
15 private array $values = [];
16
17 public function __construct( $value, ...$values ) {
18 if ( !is_string( $value ) && !( $value instanceof LikeMatch ) ) {
19 throw new InvalidArgumentException( "Value $value must be either string or LikeMatch" );
20 }
21 $this->values = [ $value ];
22
23 foreach ( $values as $value ) {
24 if ( !is_string( $value ) && !( $value instanceof LikeMatch ) ) {
25 throw new InvalidArgumentException( "Value $value must be either string or LikeMatch" );
26 }
27 $this->values[] = $value;
28 }
29 }
30
35 public function toSql( DbQuoter $dbQuoter ): string {
36 $s = '';
37
38 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
39 // may escape backslashes, creating problems of double escaping. The `
40 // character has good cross-DBMS compatibility, avoiding special operators
41 // in MS SQL like ^ and %
42 $escapeChar = '`';
43
44 foreach ( $this->values as $value ) {
45 if ( $value instanceof LikeMatch ) {
46 $s .= $value->toString();
47 } else {
48 $s .= $this->escapeLikeInternal( $value, $escapeChar );
49 }
50 }
51
52 return $dbQuoter->addQuotes( $s ) . ' ESCAPE ' . $dbQuoter->addQuotes( $escapeChar );
53 }
54
55 private function escapeLikeInternal( $s, $escapeChar = '`' ) {
56 return str_replace(
57 [ $escapeChar, '%', '_' ],
58 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
59 $s
60 );
61 }
62}
Used by Database::buildLike() to represent characters that have special meaning in SQL LIKE clauses a...
Definition LikeMatch.php:10
Content of like value.
Definition LikeValue.php:14
toSql(DbQuoter $dbQuoter)
Definition LikeValue.php:35
__construct( $value,... $values)
Definition LikeValue.php:17
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.