Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sql string #154

Open
wants to merge 6 commits into
base: development
Choose a base branch
from
Open
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
74 changes: 74 additions & 0 deletions src/DataHandling/SqlString.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

namespace CubeTools\CubeCommonBundle\DataHandling;

class SqlString
{
/**
* @var string[] from glob to sql pattern
*/
private static $replacements = [
'%' => '\%', // escape for sql like
'_' => '\_', // dito
'*' => '%',
'?' => '_',
];

/**
* Convertes a (glob) string to a string for sql like.
*
* @param string $submitted like typed from the user
*
* @return string for sql like
*/
public static function toLikeString($submitted)
{
$pattern = self::toLikePatterns($submitted);
if ('' === $pattern) {
return $pattern; // without % at both sides
} elseif ($submitted !== $pattern) {
return $pattern;
} else {
// pre- and append %
return '%'.$pattern.'%';
}
}

/**
* Convertes a string for sql like to a (glob) string to show to the user.
*
* @param string $forSql
*
* @return string to show to the user
*/
public static function fromLikeString($forSql)
{
if (static::hasSqlPatternOnlyAtEnds($forSql)) {
// has % at start and end only
$forUser = substr($forSql, 1, -1);
} else {
$forUser = $forSql;
}

return self::fromLikePatterns($forUser);
}

protected static function toLikePatterns($original)
{
return strtr($original, self::$replacements);
}

protected static function fromLikePatterns($submitted)
{
return strtr($submitted, array_flip(self::$replacements));
}

protected static function hasSqlPatternOnlyAtEnds($forSql)
{
return '%' === substr($forSql, 0, 1) && // % at start
false === strpos($forSql, '_') && // no _
false !== ($pPos = strpos($forSql, '%', 1)) && // has a 2nd %
strlen($forSql) - 1 === $pPos // % is at end
;
}
}
30 changes: 16 additions & 14 deletions src/Filter/FilterQueryCondition.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace CubeTools\CubeCommonBundle\Filter;

use CubeTools\CubeCommonBundle\DataHandling\SqlString;
use CubeTools\CubeCommonBundle\Form\EventListener\AnyNoneFilterListener;
use Doctrine\Common\Collections\ArrayCollection;

Expand All @@ -13,7 +14,7 @@ class FilterQueryCondition implements \ArrayAccess, \Countable
/**
* @var array of form elements to use for filtering
*/
private $filter = array();
private $filter = [];

/**
* @var \Doctrine\ORM\QueryBuilder
Expand All @@ -33,7 +34,7 @@ class FilterQueryCondition implements \ArrayAccess, \Countable
/**
* @param array $filter array of form elements (returned by $mainForm->getData())
*/
public function __construct(array $filter = array())
public function __construct(array $filter = [])
{
if (isset($filter[AnyNoneFilterListener::KEY_ANY_NONE_SELECTED_COLUMNS])) {
$filter[AnyNoneFilterListener::KEY_ANY_NONE_SELECTED_COLUMNS] = json_decode($filter[AnyNoneFilterListener::KEY_ANY_NONE_SELECTED_COLUMNS], true);
Expand Down Expand Up @@ -123,15 +124,15 @@ public function count()
*
* @return array
*/
public function getAsParameters(array $skip = array())
public function getAsParameters(array $skip = [])
{
$filter = $this->filter;
if ($skip) {
$filter = array_diff_key($filter, array_fill_keys($skip, null));
}
$actFilter = array_filter($filter, array($this, 'isAnActiveValue'));
$actFilter = array_filter($filter, [$this, 'isAnActiveValue']);

return array_map(array($this, 'toParameterValue'), $actFilter);
return array_map([$this, 'toParameterValue'], $actFilter);
}

/**
Expand Down Expand Up @@ -185,10 +186,10 @@ public function isAnyOrNoneValue($name, $dbColName)
{
if (isset($this->filter[$name]) && is_scalar($this->filter[$name])) {
$value = str_replace('%', '', $this->filter[$name]);
} else if (isset($this->filter[AnyNoneFilterListener::KEY_ANY_NONE_SELECTED_COLUMNS])) {
} elseif (isset($this->filter[AnyNoneFilterListener::KEY_ANY_NONE_SELECTED_COLUMNS])) {
if (in_array($name, $this->filter[AnyNoneFilterListener::KEY_ANY_NONE_SELECTED_COLUMNS][AnyNoneFilterListener::KEY_ANY_COLUMNS])) {
$value = $this->isAny;
} else if (in_array($name, $this->filter[AnyNoneFilterListener::KEY_ANY_NONE_SELECTED_COLUMNS][AnyNoneFilterListener::KEY_NONE_COLUMNS])) {
} elseif (in_array($name, $this->filter[AnyNoneFilterListener::KEY_ANY_NONE_SELECTED_COLUMNS][AnyNoneFilterListener::KEY_NONE_COLUMNS])) {
$value = $this->isNone;
} else {
$value = false;
Expand Down Expand Up @@ -262,6 +263,7 @@ public function andWhereLike($table, $filterName, $dbColumn = null)
$dbColName = $this->getDbColumn($table, $filterName, $dbColumn);

if ($this->isActive($filterName) && !$this->isAnyOrNoneValue($filterName, $dbColName)) {
// the value is already converted to "like string"
$value = $this->filter[$filterName];
$param = $filterName;
$this->qb->andWhere($dbColName.' LIKE :'.$param.' OR '.$dbColName.' LIKE :'.$param.'_htmlentities')->setParameter($param, $value)->setParameter($param.'_htmlentities', htmlentities($value));
Expand All @@ -275,9 +277,9 @@ public function andWhereLikeWildcard($table, $filterName, $dbColumn = null)
$dbColName = $this->getDbColumn($table, $filterName, $dbColumn);

if (!$this->isAnyOrNoneValue($filterName, $dbColName) && $this->isActive($filterName)) {
$value = $this->filter[$filterName];
$value = SqlString::toLikeString($this->filter[$filterName]);
$param = $filterName;
$this->qb->andWhere($dbColName.' LIKE :'.$param.' OR '.$dbColName.' LIKE :'.$param.'_htmlentities')->setParameter($param, '%'.$value.'%')->setParameter($param.'_htmlentities', '%'.htmlentities($value).'%');
$this->qb->andWhere($dbColName.' LIKE :'.$param.' OR '.$dbColName.' LIKE :'.$param.'_htmlentities')->setParameter($param, $value)->setParameter($param.'_htmlentities', htmlentities($value));
}

return $this;
Expand Down Expand Up @@ -327,7 +329,7 @@ public function andWhereInArray($table, $filterName, $dbColumn = null, $arrayTyp
$value = $value->toArray();
}

$parameters = array();
$parameters = [];
foreach ($value as $elementKey => $elementValue) {
$parameterKey = $filterName.$elementKey;
switch ($arrayType) {
Expand All @@ -342,7 +344,7 @@ public function andWhereInArray($table, $filterName, $dbColumn = null, $arrayTyp
$this->qb->setParameter($parameterKey, $parameterValue);
}

$likeQueryArray = array();
$likeQueryArray = [];
foreach ($parameters as $parameterName => $parameterValue) {
$likeQueryArray[] = sprintf("%s LIKE :%s", $dbColName, $parameterName);
}
Expand All @@ -360,7 +362,7 @@ public function andWhereIntegerRange($table, $filterName, $dbColumn = null)
$dbColName = $this->getDbColumn($table, $filterName, $dbColumn);
$param = $filterName;
if (is_int($value)) {
$value = array('from' => $value, 'to' => $value);
$value = ['from' => $value, 'to' => $value];
}
if ($value['from']) {
$this->qb->andWhere($dbColName.' >= :'.$param.'From')->setParameter($param.'From', $value['from']);
Expand All @@ -380,7 +382,7 @@ public function andWhereDaterange($table, $filterName, $dbColumn = null)
$dbColName = $this->getDbColumn($table, $filterName, $dbColumn);
$param = $filterName;
if ($value instanceof \DateTimeInterface) {
$value = array('from' => $value, 'to' => $value);
$value = ['from' => $value, 'to' => $value];
}
if ($value['from']) {
$this->qb->andWhere($dbColName.' >= :'.$param.'From')->setParameter($param.'From', $value['from']);
Expand Down Expand Up @@ -475,7 +477,7 @@ public function __call($method, $args)
if ($this->qb instanceof FilterEntityQueryBuilder && $method !== 'leftJoin') {
return $this;
} else {
$callback = array($this->qb, $method);
$callback = [$this->qb, $method];
if (!is_callable($callback)) {
$msg = "Undefined method '$method' (not in ".static::class;
if ($this->qb && is_object($this->qb)) {
Expand Down
53 changes: 53 additions & 0 deletions tests/DataHandling/SqlStringTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace Tests\CubeTools\CubeCommonBundle\DataHandling;

use CubeTools\CubeCommonBundle\DataHandling\SqlString;
use PHPUnit\Framework\TestCase;

class SqlStringTest extends TestCase
{
private static $toLike = [
// forSql, forUser, [forSql expected fromLikeString]
['%9876%', '9876'],
['%i3,dz', '*i3,dz'],
['zu6%jr2', 'zu6*jr2'],
['pjTe%', 'pjTe*'],
['%43jt%', '*43jt*', '43jt'],
['%9g3%hwks%', '*9g3*hwks*'],
['rwqk_je', 'rwqk?je'],
['tex\_xu', 'tex_xu'], // would be better for [0]: '%tex\_xu%' instead of 'tex\_xu'
['us\%98', 'us%98'], // would be better for [0]: '%us\%98%' instead of 'us\%98'
['%oZ\_%', '*oZ_*'], // would be better for [2]: 'oZ\_' (instead of same as [0])
['_\_yIU', '?_yIU'],
['Q%i\%', 'Q*i%'],
];

public function testToLikeString()
{
$toLike = self::$toLike;

foreach ($toLike as $toTest) {
$expected = $toTest[0];
$fromUser = $toTest[1];
$forSql = SqlString::toLikeString($fromUser);
$this->assertSame($expected, $forSql, 'fromUser: '.$fromUser);
if (isset($toTest[2])) {
$fromUser = $toTest[2];
$forSql = SqlString::toLikeString($fromUser);
$this->assertSame($expected, $forSql, 'fromUser: '.$fromUser);
}
}
}

public function testFromLikeString()
{
$toLike = self::$toLike;

foreach ($toLike as $toTest) {
$expected = isset($toTest[2]) ? $toTest[2] : $toTest[1];
$forSql = $toTest[0];
$this->assertSame($expected, SqlString::fromLikeString($forSql), 'forSql: '.$forSql);
}
}
}