orm icon indicating copy to clipboard operation
orm copied to clipboard

Add "when()" method to QueryBuilder to be more readable conditional query

Open iku12phycho opened this issue 1 year ago • 0 comments

Feature Request

Hello, Code visibility is good if Query Builder is more Declarative.

Q A
New Feature yes
RFC no
BC Break no

Summary

add when()method to contain condition statements. nests and if statements are less.

when()method has follow arguments

  • $condition (boolean)
  • $truthy (Closure) run if $condition is true
  • $falsy(Closure|null) run if $condition is false. when it is null, skip.

before

// switch null clause
if ($label === null) {
  $queryBuilder->where(`label is :label`)
    ->setParameter( 'label', $label);
}else {
  $queryBuilder->where(`label = :label`)
    ->setParameter( 'label', $label);
}
// conditional clause
if (!$isAdmin) {
  $queryBuilder->addWhere('isPublic = true');
}

after

$queryBuilder->when(
  condition: $label === null,
  truthy: fn ($queryBuilder) => $queryBuilder->where(`label is :label`),
  falsy: fn ($queryBuilder) => $queryBuilder->where(`label = :label`)
)
->setParameter( 'label', $label)
->when(!$isAdmin, fn ($queryBuilder) => $queryBuilder->addWhere('isPublic = true'))
;

iku12phycho avatar Mar 12 '24 09:03 iku12phycho