MediaWiki master
LikeValue.php
Go to the documentation of this file.
1<?php
2
3namespace Wikimedia\Rdbms;
4
5use InvalidArgumentException;
7
14class LikeValue {
16 private array $values = [];
17
22 public function __construct( $value, ...$values ) {
23 if ( !is_string( $value ) && !( $value instanceof LikeMatch ) ) {
24 $type = is_object( $value ) ? get_class( $value ) : gettype( $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 = is_object( $value ) ? get_class( $value ) : gettype( $value );
32 throw new InvalidArgumentException( "\$value must be string or LikeMatch, got $type" );
33 }
34 $this->values[] = $value;
35 }
36 }
37
42 public function toSql( DbQuoter $dbQuoter ): string {
43 $s = '';
44
45 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
46 // may escape backslashes, creating problems of double escaping. The `
47 // character has good cross-DBMS compatibility, avoiding special operators
48 // in MS SQL like ^ and %
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}
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:42
__construct( $value,... $values)
Definition LikeValue.php:22
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.