Skip to content

Instantly share code, notes, and snippets.

@gurucomkz
Created August 25, 2020 05:39
Show Gist options
  • Save gurucomkz/ed1aeccf6f356034067223b1d30f1425 to your computer and use it in GitHub Desktop.
Save gurucomkz/ed1aeccf6f356034067223b1d30f1425 to your computer and use it in GitHub Desktop.
Silverstripe4 allows to combine AND and OR clauses in ORM filtering
<?php
namespace App\Extensions;
/*
Config
```
SilverStripe\ORM\DataList:
extensions:
- App\Extensions\DataFilterAnyMultiExtension
```
*/
use SilverStripe\ORM\DataExtension;
class DataFilterAnyMultiExtension extends DataExtension {
public function filterAnyMulti() {
$whereArgumentsCombo = func_get_args();
return $this->owner->alterDataQuery(function($query, $list) use ($whereArgumentsCombo) {
$ORquery = $query->disjunctiveGroup();
foreach($whereArgumentsCombo as $whereArguments){
$ANDquery = $ORquery->conjunctiveGroup();
foreach($whereArguments as $field => $value) {
$fieldArgs = explode(':',$field);
$field = array_shift($fieldArgs);
$filterType = array_shift($fieldArgs);
$modifiers = $fieldArgs;
// This is here since PHP 5.3 can't call protected/private methods in a closure.
$t = singleton($list->dataClass())->dbObject($field);
if($filterType) {
$className = "{$filterType}Filter";
} else {
$className = 'ExactMatchFilter';
}
if(!class_exists($className)){
$className = 'ExactMatchFilter';
array_unshift($modifiers, $filterType);
}
$t = new $className($field, $value, $modifiers);
$t->apply($ANDquery);
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment