View source
<?php
namespace Drupal\Tests\sqlsrv\Unit;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\Query\PlaceholderInterface;
use Drupal\sqlsrv\Driver\Database\sqlsrv\Condition;
use Drupal\Tests\UnitTestCase;
use Prophecy\Argument;
class SqlsrvConditionTest extends UnitTestCase {
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());
}
public function dataProviderForTestLike() {
return [
[
'%',
'%',
],
[
'\\%',
'[%]',
],
[
'\\_',
'[_]',
],
[
'\\\\',
'\\',
],
[
'[\\%]',
'[[][%]]',
],
];
}
public function testRegexp($expected, $field_name, $operator, $pattern) {
$connection = $this
->prophesize(Connection::class);
$connection
->escapeField($field_name)
->will(function ($args) {
return preg_replace('/[^A-Za-z0-9_.]+/', '', $args[0]);
});
$connection
->mapConditionOperator($operator)
->willReturn([
'operator' => $operator,
]);
$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($field_name, $pattern, $operator);
$condition
->compile($connection, $query_placeholder);
$this
->assertEquals($expected, $condition
->__toString());
$this
->assertEquals([
':db_condition_placeholder_0' => $pattern,
], $condition
->arguments());
}
public function dataProviderForTestRegexp() {
return [
[
'(REGEXP(:db_condition_placeholder_0, name) = 1)',
'name',
'REGEXP',
'^P',
],
[
'(REGEXP(:db_condition_placeholder_0, name123) = 1)',
'name-123',
'REGEXP',
's$',
],
[
'(REGEXP(:db_condition_placeholder_0, name) = 0)',
'name',
'NOT REGEXP',
'^\\$[a-z][a-zA-Z_]$',
],
[
'(REGEXP(:db_condition_placeholder_0, name123) = 0)',
'name-123',
'NOT REGEXP',
'^[a-z].*$',
],
];
}
}