You are here

public function SqlsrvConditionTest::testLike in Drupal driver for SQL Server and SQL Azure 4.2.x

Same name and namespace in other branches
  1. 8.2 tests/src/Unit/SqlsrvConditionTest.php \Drupal\Tests\sqlsrv\Unit\SqlsrvConditionTest::testLike()
  2. 3.0.x tests/src/Unit/SqlsrvConditionTest.php \Drupal\Tests\sqlsrv\Unit\SqlsrvConditionTest::testLike()
  3. 3.1.x tests/src/Unit/SqlsrvConditionTest.php \Drupal\Tests\sqlsrv\Unit\SqlsrvConditionTest::testLike()
  4. 4.0.x tests/src/Unit/SqlsrvConditionTest.php \Drupal\Tests\sqlsrv\Unit\SqlsrvConditionTest::testLike()
  5. 4.1.x tests/src/Unit/SqlsrvConditionTest.php \Drupal\Tests\sqlsrv\Unit\SqlsrvConditionTest::testLike()

Test the escaping strategy of the LIKE operator.

Mysql, Postgres, and sqlite all use '\' to escape '%' and '_' in the LIKE statement. SQL Server can also use a backslash with the syntax. field LIKE :text ESCAPE '\'. However, due to a bug in PDO (https://bugs.php.net/bug.php?id=79276), if a SQL statement has multiple LIKE statements, parameters are not correctly replaced if they are located between a pair of backslashes:

"field1 LIKE :text1 ESCAPE '\' AND field2 LIKE :text2 ESCAPE '\'" :text2 will not be replaced.

If the PDO bug is fixed, this test and the LIKE customization within the Condition class can be removed

@dataProvider dataProviderForTestLike

File

tests/src/Unit/SqlsrvConditionTest.php, line 38

Class

SqlsrvConditionTest
Test the behavior of the custom Condition class.

Namespace

Drupal\Tests\sqlsrv\Unit

Code

public function testLike($given, $expected) {
  $connection = $this
    ->prophesize(Connection::class);
  $connection
    ->escapeField(Argument::any())
    ->will(function ($args) {
    return preg_replace('/[^A-Za-z0-9_.]+/', '', $args[0]);
  });
  $connection
    ->mapConditionOperator(Argument::any())
    ->willReturn([]);
  $connection = $connection
    ->reveal();
  $query_placeholder = $this
    ->prophesize(PlaceholderInterface::class);
  $counter = 0;
  $query_placeholder
    ->nextPlaceholder()
    ->will(function () use (&$counter) {
    return $counter++;
  });
  $query_placeholder
    ->uniqueIdentifier()
    ->willReturn(4);
  $query_placeholder = $query_placeholder
    ->reveal();
  $condition = new Condition('AND');
  $condition
    ->condition('name', $given, 'LIKE');
  $condition
    ->compile($connection, $query_placeholder);
  $this
    ->assertEquals('name LIKE :db_condition_placeholder_0', $condition
    ->__toString());
  $this
    ->assertEquals([
    ':db_condition_placeholder_0' => $expected,
  ], $condition
    ->arguments());
}