Skip to content

Commit 0645d3d

Browse files
committed
refactor(database): centralize builder condition handling
- Route WHERE/HAVING condition insertion through shared prefix handling - Extract WHERE/HAVING condition compilation into focused private helpers - Add regression coverage for operator and null condition handling - Reduce the BaseBuilder empty() PHPStan baseline count Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent 37b8b37 commit 0645d3d

3 files changed

Lines changed: 159 additions & 107 deletions

File tree

‎system/Database/BaseBuilder.php‎

Lines changed: 121 additions & 106 deletions
Original file line numberDiff line numberDiff line change
@@ -855,16 +855,14 @@ protected function whereColumnHaving(string $qbKey, string $first, string $secon
855855

856856
$escape ??= $this->db->protectIdentifiers;
857857

858-
$prefix = $this->{$qbKey} === [] ? $this->groupGetType('') : $this->groupGetType($type);
859-
860-
$this->{$qbKey}[] = [
858+
$this->addWhereHavingCondition($qbKey, [
861859
'columnComparison' => true,
862-
'condition' => $prefix,
860+
'condition' => '',
863861
'escape' => $escape,
864862
'first' => $first,
865863
'operator' => $operator,
866864
'second' => $second,
867-
];
865+
], $type);
868866

869867
return $this;
870868
}
@@ -977,17 +975,15 @@ private function whereBetweenHaving(string $qbKey, ?string $key = null, $values
977975
$lowerBind = $this->setBind($key, $values[0], $escape);
978976
$upperBind = $this->setBind($key, $values[1], $escape);
979977
$not = $not ? ' NOT' : '';
980-
$prefix = $this->{$qbKey} === [] ? $this->groupGetType('') : $this->groupGetType($type);
981-
982-
$this->{$qbKey}[] = [
978+
$this->addWhereHavingCondition($qbKey, [
983979
'betweenComparison' => true,
984-
'condition' => $prefix,
980+
'condition' => '',
985981
'escape' => $escape,
986982
'key' => $key,
987983
'lowerBind' => $lowerBind,
988984
'not' => $not,
989985
'upperBind' => $upperBind,
990-
];
986+
], $type);
991987

992988
return $this;
993989
}
@@ -1010,13 +1006,12 @@ protected function whereExistsSubquery($subquery, bool $not = false, string $typ
10101006
throw new InvalidArgumentException(sprintf('%s() expects $subquery to be of type BaseBuilder or closure', debug_backtrace(0, 2)[1]['function']));
10111007
}
10121008

1013-
$prefix = $this->QBWhere === [] ? $this->groupGetType('') : $this->groupGetType($type);
10141009
$operator = $not ? 'NOT EXISTS' : 'EXISTS';
10151010

1016-
$this->QBWhere[] = [
1017-
'condition' => "{$prefix}{$operator} {$this->buildSubquery($subquery, true)}",
1011+
$this->addWhereHavingCondition('QBWhere', [
1012+
'condition' => "{$operator} {$this->buildSubquery($subquery, true)}",
10181013
'escape' => false,
1019-
];
1014+
], $type);
10201015

10211016
return $this;
10221017
}
@@ -1055,8 +1050,6 @@ protected function whereHaving(string $qbKey, $key, $value = null, string $type
10551050
}
10561051

10571052
foreach ($keyValue as $k => $v) {
1058-
$prefix = empty($this->{$qbKey}) ? $this->groupGetType('') : $this->groupGetType($type);
1059-
10601053
if ($rawSqlOnly) {
10611054
$k = '';
10621055
$op = '';
@@ -1104,22 +1097,42 @@ protected function whereHaving(string $qbKey, $key, $value = null, string $type
11041097
$op = '';
11051098
}
11061099

1100+
$condition = $k . $op . $v;
1101+
11071102
if ($v instanceof RawSql) {
1108-
$this->{$qbKey}[] = [
1109-
'condition' => $v->with($prefix . $k . $op . $v),
1110-
'escape' => $escape,
1111-
];
1112-
} else {
1113-
$this->{$qbKey}[] = [
1114-
'condition' => $prefix . $k . $op . $v,
1115-
'escape' => $escape,
1116-
];
1103+
$condition = $v->with($condition);
11171104
}
1105+
1106+
$this->addWhereHavingCondition($qbKey, [
1107+
'condition' => $condition,
1108+
'escape' => $escape,
1109+
], $type);
11181110
}
11191111

11201112
return $this;
11211113
}
11221114

1115+
/**
1116+
* @param array<string, mixed> $condition
1117+
*/
1118+
private function addWhereHavingCondition(string $clause, array $condition, string $type): void
1119+
{
1120+
$prefix = $this->getWhereHavingPrefix($clause, $type);
1121+
1122+
if ($condition['condition'] instanceof RawSql) {
1123+
$condition['condition'] = $condition['condition']->with($prefix . $condition['condition']);
1124+
} else {
1125+
$condition['condition'] = $prefix . $condition['condition'];
1126+
}
1127+
1128+
$this->{$clause}[] = $condition;
1129+
}
1130+
1131+
private function getWhereHavingPrefix(string $clause, string $type): string
1132+
{
1133+
return $this->{$clause} === [] ? $this->groupGetType('') : $this->groupGetType($type);
1134+
}
1135+
11231136
/**
11241137
* Generates a WHERE field IN('item', 'item') SQL query,
11251138
* joined with 'AND' if appropriate.
@@ -1268,14 +1281,10 @@ protected function _whereIn(?string $key = null, $values = null, bool $not = fal
12681281

12691282
$ok = $this->setBind($ok, $whereIn, $escape);
12701283

1271-
$prefix = empty($this->{$clause}) ? $this->groupGetType('') : $this->groupGetType($type);
1272-
1273-
$whereIn = [
1274-
'condition' => "{$prefix}{$key}{$not} IN :{$ok}:",
1284+
$this->addWhereHavingCondition($clause, [
1285+
'condition' => "{$key}{$not} IN :{$ok}:",
12751286
'escape' => false,
1276-
];
1277-
1278-
$this->{$clause}[] = $whereIn;
1287+
], $type);
12791288

12801289
return $this;
12811290
}
@@ -1408,7 +1417,7 @@ protected function _like($field, string $match = '', string $type = 'AND ', stri
14081417
$v = $match;
14091418
$insensitiveSearch = false;
14101419

1411-
$prefix = empty($this->{$clause}) ? $this->groupGetType('') : $this->groupGetType($type);
1420+
$prefix = $this->getWhereHavingPrefix($clause, $type);
14121421

14131422
if ($side === 'none') {
14141423
$bind = $this->setBind($field->getBindingKey(), $v, $escape);
@@ -1442,7 +1451,7 @@ protected function _like($field, string $match = '', string $type = 'AND ', stri
14421451
$v = mb_strtolower($v, 'UTF-8');
14431452
}
14441453

1445-
$prefix = empty($this->{$clause}) ? $this->groupGetType('') : $this->groupGetType($type);
1454+
$prefix = $this->getWhereHavingPrefix($clause, $type);
14461455

14471456
if ($side === 'none') {
14481457
$bind = $this->setBind($k, $v, $escape);
@@ -3479,98 +3488,104 @@ protected function compileWhereHaving(string $qbKey): string
34793488
{
34803489
if (! empty($this->{$qbKey})) {
34813490
foreach ($this->{$qbKey} as &$qbkey) {
3482-
// Is this condition already compiled?
3483-
if (is_string($qbkey)) {
3484-
continue;
3485-
}
3491+
$qbkey = $this->compileWhereHavingCondition($qbkey);
3492+
}
34863493

3487-
if ($qbkey instanceof RawSql) {
3488-
continue;
3489-
}
3494+
return ($qbKey === 'QBHaving' ? "\nHAVING " : "\nWHERE ")
3495+
. implode("\n", $this->{$qbKey});
3496+
}
3497+
3498+
return '';
3499+
}
34903500

3491-
if ($qbkey['condition'] instanceof RawSql) {
3492-
$qbkey = $qbkey['condition'];
3501+
/**
3502+
* @used-by compileWhereHaving()
3503+
*
3504+
* @param array<string, mixed>|RawSql|string $condition
3505+
*/
3506+
private function compileWhereHavingCondition(array|RawSql|string $condition): RawSql|string
3507+
{
3508+
// Is this condition already compiled?
3509+
if (is_string($condition) || $condition instanceof RawSql) {
3510+
return $condition;
3511+
}
34933512

3494-
continue;
3495-
}
3513+
if ($condition['condition'] instanceof RawSql) {
3514+
return $condition['condition'];
3515+
}
34963516

3497-
if (($qbkey['columnComparison'] ?? false) === true) {
3498-
$qbkey = $this->compileColumnComparison($qbkey);
3517+
if (($condition['columnComparison'] ?? false) === true) {
3518+
return $this->compileColumnComparison($condition);
3519+
}
34993520

3500-
continue;
3501-
}
3521+
if (($condition['betweenComparison'] ?? false) === true) {
3522+
return $this->compileBetweenComparison($condition);
3523+
}
35023524

3503-
if (($qbkey['betweenComparison'] ?? false) === true) {
3504-
$qbkey = $this->compileBetweenComparison($qbkey);
3525+
if ($condition['escape'] === false) {
3526+
return $condition['condition'];
3527+
}
35053528

3506-
continue;
3507-
}
3529+
return $this->compileEscapedCondition($condition['condition']);
3530+
}
35083531

3509-
if ($qbkey['escape'] === false) {
3510-
$qbkey = $qbkey['condition'];
3532+
/**
3533+
* @used-by compileWhereHavingCondition()
3534+
*/
3535+
private function compileEscapedCondition(string $condition): string
3536+
{
3537+
// Split multiple conditions
3538+
$conditions = preg_split(
3539+
'/((?:^|\s+)AND\s+|(?:^|\s+)OR\s+)/i',
3540+
$condition,
3541+
-1,
3542+
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY,
3543+
);
35113544

3512-
continue;
3513-
}
3545+
foreach ($conditions as &$condition) {
3546+
$op = $this->getOperator($condition);
3547+
if (
3548+
$op === false
3549+
|| preg_match(
3550+
'/^(\(?)(.*)(' . preg_quote($op, '/') . ')\s*(.*(?<!\)))?(\)?)$/i',
3551+
$condition,
3552+
$matches,
3553+
) !== 1
3554+
) {
3555+
continue;
3556+
}
35143557

3515-
// Split multiple conditions
3516-
$conditions = preg_split(
3517-
'/((?:^|\s+)AND\s+|(?:^|\s+)OR\s+)/i',
3518-
$qbkey['condition'],
3519-
-1,
3520-
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY,
3521-
);
3522-
3523-
foreach ($conditions as &$condition) {
3524-
$op = $this->getOperator($condition);
3525-
if (
3526-
$op === false
3527-
|| preg_match(
3528-
'/^(\(?)(.*)(' . preg_quote($op, '/') . ')\s*(.*(?<!\)))?(\)?)$/i',
3529-
$condition,
3530-
$matches,
3531-
) !== 1
3532-
) {
3533-
continue;
3534-
}
3558+
// $matches = [
3559+
// 0 => '(test <= foo)', /* the whole thing */
3560+
// 1 => '(', /* optional */
3561+
// 2 => 'test', /* the field name */
3562+
// 3 => ' <= ', /* $op */
3563+
// 4 => 'foo', /* optional, if $op is e.g. 'IS NULL' */
3564+
// 5 => ')' /* optional */
3565+
// ];
35353566

3536-
// $matches = [
3537-
// 0 => '(test <= foo)', /* the whole thing */
3538-
// 1 => '(', /* optional */
3539-
// 2 => 'test', /* the field name */
3540-
// 3 => ' <= ', /* $op */
3541-
// 4 => 'foo', /* optional, if $op is e.g. 'IS NULL' */
3542-
// 5 => ')' /* optional */
3543-
// ];
3544-
3545-
if ($matches[4] !== '') {
3546-
$protectIdentifiers = false;
3547-
if (str_contains($matches[4], '.')) {
3548-
$protectIdentifiers = true;
3549-
}
3550-
3551-
if (! str_contains($matches[4], ':')) {
3552-
$matches[4] = $this->db->protectIdentifiers(trim($matches[4]), false, $protectIdentifiers);
3553-
}
3554-
3555-
$matches[4] = ' ' . $matches[4];
3556-
}
3567+
if ($matches[4] !== '') {
3568+
$protectIdentifiers = false;
3569+
if (str_contains($matches[4], '.')) {
3570+
$protectIdentifiers = true;
3571+
}
35573572

3558-
$condition = $matches[1] . $this->db->protectIdentifiers(trim($matches[2]))
3559-
. ' ' . trim($matches[3]) . $matches[4] . $matches[5];
3573+
if (! str_contains($matches[4], ':')) {
3574+
$matches[4] = $this->db->protectIdentifiers(trim($matches[4]), false, $protectIdentifiers);
35603575
}
35613576

3562-
$qbkey = implode('', $conditions);
3577+
$matches[4] = ' ' . $matches[4];
35633578
}
35643579

3565-
return ($qbKey === 'QBHaving' ? "\nHAVING " : "\nWHERE ")
3566-
. implode("\n", $this->{$qbKey});
3580+
$condition = $matches[1] . $this->db->protectIdentifiers(trim($matches[2]))
3581+
. ' ' . trim($matches[3]) . $matches[4] . $matches[5];
35673582
}
35683583

3569-
return '';
3584+
return implode('', $conditions);
35703585
}
35713586

35723587
/**
3573-
* @used-by compileWhereHaving()
3588+
* @used-by compileWhereHavingCondition()
35743589
*
35753590
* @param array{columnComparison: true, condition: string, escape: bool, first: string, operator: string, second: string} $condition
35763591
*/
@@ -3585,7 +3600,7 @@ private function compileColumnComparison(array $condition): string
35853600
}
35863601

35873602
/**
3588-
* @used-by compileWhereHaving()
3603+
* @used-by compileWhereHavingCondition()
35893604
*
35903605
* @param array{betweenComparison: true, condition: string, escape: bool, key: string, lowerBind: string, not: string, upperBind: string} $condition
35913606
*/

‎tests/system/Database/Builder/WhereTest.php‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,43 @@ public function testWhereLikeInAssociateArray(): void
151151
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
152152
}
153153

154+
/**
155+
* @param mixed $value
156+
*/
157+
#[DataProvider('provideWhereOperatorRegressionCases')]
158+
public function testWhereOperatorRegressionCases(string $key, $value, string $expectedSQL): void
159+
{
160+
$builder = $this->db->table('jobs job');
161+
162+
$builder->where($key, $value);
163+
164+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
165+
}
166+
167+
/**
168+
* @return iterable<string, array{string, mixed, string}>
169+
*/
170+
public static function provideWhereOperatorRegressionCases(): iterable
171+
{
172+
return [
173+
'like operator with value' => [
174+
'job.status LIKE',
175+
'p%',
176+
'SELECT * FROM "jobs" "job" WHERE "job"."status" LIKE \'p%\'',
177+
],
178+
'equals operator with null' => [
179+
'job.deleted_at =',
180+
null,
181+
'SELECT * FROM "jobs" "job" WHERE "job"."deleted_at" IS NULL',
182+
],
183+
'not equals operator with null' => [
184+
'job.deleted_at !=',
185+
null,
186+
'SELECT * FROM "jobs" "job" WHERE "job"."deleted_at" IS NOT NULL',
187+
],
188+
];
189+
}
190+
154191
public function testWhereCustomString(): void
155192
{
156193
$builder = $this->db->table('jobs');

‎utils/phpstan-baseline/empty.notAllowed.neon‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ parameters:
3434

3535
-
3636
message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#'
37-
count: 28
37+
count: 24
3838
path: ../../system/Database/BaseBuilder.php
3939

4040
-

0 commit comments

Comments
 (0)