Skip to content

Instantly share code, notes, and snippets.

@vojtech-dobes
Last active August 29, 2015 14:02
Show Gist options
  • Save vojtech-dobes/bdfb70b2f0677fb93323 to your computer and use it in GitHub Desktop.
Save vojtech-dobes/bdfb70b2f0677fb93323 to your computer and use it in GitHub Desktop.
Filtering helper useful for grids (or dynamic building of conditions)
<?php
// $selection instanceof DibiFluent
$filter = FilterHelper::start($selection, $filter)
->add('start_date')->setRule('[b.start_date] >= %d')
->add('end_date')->setRule('[b.end_date] <= %d')
->end();
<?php
use DibiFluent;
use Nette\ArrayHash;
class FilterHelper
{
/** @var DibiFluent */
private $selection;
/** @var ArrayHash */
private $filter;
/** @var string */
private $currentColumn;
public function __construct(DibiFluent $selection, array $filter)
{
$this->selection = $selection;
$this->filter = ArrayHash::from($filter);
}
/**
* Sets column of new rule.
*
* @param string
*
* @return FilterHelper provides a fluent interface
*/
public function add($column)
{
$this->currentColumn = $column;
return $this;
}
/**
* Sets arguments of new rule.
*
* @param mixed ...
*
* @return FilterHelper provides a fluent interface
*/
public function setRule()
{
if (isset($this->filter[$this->currentColumn])) {
$args = func_get_args();
$args[] = $this->filter[$this->currentColumn];
call_user_func_array([$this->selection, 'where'], $args);
unset($this->filter[$this->currentColumn]);
}
$this->currentColumn = NULL;
return $this;
}
/**
* Adds rule %LIKE%
*
* @param string
* @param string|NULL
*/
public function like($value, $column = NULL)
{
return $this->setRule('%n LIKE %~like~', $column ? : $this->currentColumn);
}
/**
* @return array
*/
public function end()
{
return iterator_to_array($this->filter);
}
public static function start(DibiFluent $selection, array $filter)
{
return new self($selection, $filter);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment