apply not recurring and split scopes by default

This commit is contained in:
Denis Duliçi
2022-06-05 03:33:26 +03:00
parent 3ac8186d4a
commit 2cdeaad00d
10 changed files with 72 additions and 33 deletions

View File

@@ -4,7 +4,6 @@ namespace App\Traits;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
trait Scopes
{
@@ -15,30 +14,43 @@ trait Scopes
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function applyTypeScope(Builder $builder, Model $model)
public function applyNotRecurringScope(Builder $builder, Model $model)
{
// Getting type from request causes lots of issues
// @todo Try event/listener similar to Permissions trait
return;
// Skip if already exists
if ($this->scopeExists($builder, 'type')) {
// Skip if recurring is explicitly set
if ($this->scopeEquals($builder, 'type', 'like', '%-recurring')) {
return;
}
// No request in console
if (app()->runningInConsole()) {
// Skip if scope is already applied
if ($this->scopeEquals($builder, 'type', 'not like', '%-recurring')) {
return;
}
$type = $this->getTypeFromRequest();
// Apply not recurring scope
$builder->isNotRecurring();
}
if (empty($type)) {
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function applyNotSplitScope(Builder $builder, Model $model)
{
// Skip if split is explicitly set
if ($this->scopeEquals($builder, 'type', 'like', '%-split')) {
return;
}
// Apply type scope
$builder->where($model->getTable() . '.type', '=', $type);
// Skip if scope is already applied
if ($this->scopeEquals($builder, 'type', 'not like', '%-split')) {
return;
}
// Apply not split scope
$builder->isNotSplit();
}
/**
@@ -73,18 +85,43 @@ trait Scopes
return false;
}
public function getTypeFromRequest()
/**
* Check if scope has the exact value.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param $column
* @return boolean
*/
public function scopeEquals($builder, $column, $operator, $value)
{
$type = '';
$request = request();
$query = $builder->getQuery();
// Skip type scope in dashboard and reports
if ($request->routeIs('dashboards.*') || $request->routeIs('reports.*')) {
return $type;
foreach ((array) $query->wheres as $key => $where) {
if (empty($where) || empty($where['column']) || empty($where['operator']) || empty($where['value'])) {
continue;
}
if (strstr($where['column'], '.')) {
$whr = explode('.', $where['column']);
$where['column'] = $whr[1];
}
if ($where['column'] != $column) {
continue;
}
if ($where['operator'] != $operator) {
continue;
}
if ($where['value'] != $value) {
continue;
}
return true;
}
$type = $request->get('type') ?: Str::singular((string) $request->segment(3));
return $type;
return false;
}
}