Skip to content

Commit

Permalink
filtan: added second filter parameter as focus, to let client pass th…
Browse files Browse the repository at this point in the history
…e main focused function to execute while filtering
  • Loading branch information
patiencemanzen committed Nov 10, 2022
1 parent e2b443f commit 854eb05
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 14 deletions.
5 changes: 2 additions & 3 deletions src/Filterable.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
namespace Patienceman\Filtan;

use Illuminate\Database\Eloquent\Builder;

trait Filterable {
/**
* Get the parsed builder and pass it to QueryFilter for continues
Expand All @@ -11,7 +10,7 @@ trait Filterable {
* @param Builder $builder
* @param QueryFilter $filter
*/
public function scopeFilter(Builder $builder, QueryFilter $filter) {
$filter->apply($builder);
public function scopeFilter(Builder $builder, QueryFilter $filter, array $focus = []) {
$filter->apply($builder, $focus);
}
}
51 changes: 40 additions & 11 deletions src/QueryFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,28 +29,57 @@ public function __construct(Request $request) {
$this->request = $request;
}

/**
* map focuses to the main target
*
* @param array $target
* @param array $focus
* @return array
*/
public function findFocuses($target, $focus) {
$focused = [];
foreach($focus as $f)
$focused[$f] = $target[$f];
return $focused;
}

/**
* Apply builder and call each associated query string function
*/
public function apply($builder) {
public function apply($builder, array $focus) {
$this->builder = $builder;

if($focus && $this->fields())
foreach ($this->findFocuses($this->fields(), $focus) as $field => $value)
$this->caller($field, $value);

/**
* Loop over all query strings and call associated function
* from the class that extended this
*/
foreach ($this->fields() as $field => $value) {
$method = Str::camel($field);
if(!$focus)
foreach ($this->fields() as $field => $value)
$this->caller($field, $value);
}

/**
* Check is formed method already
* exist in this class
*/
if (method_exists($this, $method)) {
/**
* Call customer user function
*
* @param string $field
* @param string $value
* @return void
*/
public function caller($field, $value) {
$method = Str::camel($field);

/**
* Check is formed method already
* exist in this class
*/
if (method_exists($this, $method)) {

// then call method from this class and pass the values
call_user_func_array([$this, $method], (array)strtolower($value));
}
// then call method from this class and pass the values
call_user_func_array([$this, $method], (array)strtolower($value));
}
}

Expand Down

0 comments on commit 854eb05

Please sign in to comment.