akaunting/app/Traits/Scopes.php

81 lines
1.8 KiB
PHP
Raw Normal View History

2020-12-26 16:13:34 +03:00
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
trait Scopes
{
/**
* 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 applyTypeScope(Builder $builder, Model $model)
{
// Skip if already exists
if ($this->scopeExists($builder, 'type')) {
return;
}
2020-12-27 02:19:50 +03:00
// No request in console
if (app()->runningInConsole()) {
return;
}
2020-12-26 16:13:34 +03:00
// Apply type scope
2020-12-26 21:06:12 +03:00
$builder->where($model->getTable() . '.type', '=', $this->getTypeFromRequest());
2020-12-26 16:13:34 +03:00
}
/**
* Check if scope exists.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param $column
* @return boolean
*/
public function scopeExists($builder, $column)
{
$query = $builder->getQuery();
foreach ((array) $query->wheres as $key => $where) {
if (empty($where) || empty($where['column'])) {
continue;
}
if (strstr($where['column'], '.')) {
$whr = explode('.', $where['column']);
$where['column'] = $whr[1];
}
if ($where['column'] != $column) {
continue;
}
return true;
}
return false;
}
2020-12-26 21:01:11 +03:00
2020-12-26 21:06:12 +03:00
public function getTypeFromRequest()
2020-12-26 21:01:11 +03:00
{
2020-12-26 21:06:12 +03:00
$type = request()->get('type') ?: Str::singular(request()->segment(2, ''));
2020-12-26 21:01:11 +03:00
if ($type == 'revenue') {
$type = 'income';
}
if ($type == 'payment') {
$type = 'expense';
}
return $type;
}
2020-12-26 16:13:34 +03:00
}