Skip to content
Merged
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
9 changes: 9 additions & 0 deletions php/utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -1674,6 +1674,15 @@ function _proc_open_compat_win_env( $cmd, &$env ) {
* or real_escape next.
*/
function esc_like( $text ) {
global $wpdb;

// Check if the esc_like() method exists on the global $wpdb object.
// We need to do this because to ensure compatibilty layers like the
// SQLite integration plugin still work.
if ( null !== $wpdb && method_exists( $wpdb, 'esc_like' ) ) {
return $wpdb->esc_like( $text );
}

return addcslashes( $text, '_%\\' );
}

Expand Down
60 changes: 42 additions & 18 deletions tests/UtilsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -777,28 +777,52 @@ public static function dataProcOpenCompatWinEnv() {
];
}

public static function dataEscLike() {
return [
[ 'howdy%', 'howdy\\%' ],
[ 'howdy_', 'howdy\\_' ],
[ 'howdy\\', 'howdy\\\\' ],
[ 'howdy\\howdy%howdy_', 'howdy\\\\howdy\\%howdy\\_' ],
[ 'howdy\'"[[]*#[^howdy]!+)(*&$#@!~|}{=--`/.,<>?', 'howdy\'"[[]*#[^howdy]!+)(*&$#@!~|}{=--`/.,<>?' ],
];
}

/**
* Copied from core "tests/phpunit/tests/db.php" (adapted to not use `$wpdb`).
* @dataProvider dataEscLike
*/
public function test_esc_like() {
$inputs = [
'howdy%', // Single Percent.
'howdy_', // Single Underscore.
'howdy\\', // Single slash.
'howdy\\howdy%howdy_', // The works.
'howdy\'"[[]*#[^howdy]!+)(*&$#@!~|}{=--`/.,<>?', // Plain text.
];
$expected = [
'howdy\\%',
'howdy\\_',
'howdy\\\\',
'howdy\\\\howdy\\%howdy\\_',
'howdy\'"[[]*#[^howdy]!+)(*&$#@!~|}{=--`/.,<>?',
];
public function test_esc_like( $input, $expected ) {
$this->assertEquals( $expected, Utils\esc_like( $input ) );
}

foreach ( $inputs as $key => $input ) {
$this->assertEquals( $expected[ $key ], Utils\esc_like( $input ) );
/**
* @dataProvider dataEscLike
*/
public function test_esc_like_with_wpdb( $input, $expected ) {
global $wpdb;
$wpdb = $this->getMockBuilder( 'stdClass' );

// Handle different PHPUnit versions (5.7 for PHP 5.6 vs newer versions)
// This can be simplified if we drop support for PHP 5.6.
if ( method_exists( $wpdb, 'addMethods' ) ) {
$wpdb = $wpdb->addMethods( [ 'esc_like' ] );
} else {
$wpdb = $wpdb->setMethods( [ 'esc_like' ] );
}

$wpdb = $wpdb->getMock();
$wpdb->method( 'esc_like' )
->willReturn( addcslashes( $input, '_%\\' ) );
$this->assertEquals( $expected, Utils\esc_like( $input ) );
$this->assertEquals( $expected, Utils\esc_like( $input ) );
}

/**
* @dataProvider dataEscLike
*/
public function test_esc_like_with_wpdb_being_null( $input, $expected ) {
global $wpdb;
$wpdb = null;
$this->assertEquals( $expected, Utils\esc_like( $input ) );
}

/**
Expand Down
Loading