forked from akaunting/akaunting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Scopes.php
98 lines (77 loc) · 2.25 KB
/
Scopes.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?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)
{
// 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')) {
return;
}
// No request in console
if (app()->runningInConsole()) {
return;
}
$type = $this->getTypeFromRequest();
if (empty($type)) {
return;
}
// Apply type scope
$builder->where($model->getTable() . '.type', '=', $type);
}
/**
* 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;
}
public function getTypeFromRequest()
{
$type = '';
$request = request();
// Skip type scope in dashboard and reports
if ($request->routeIs('dashboards.*') || $request->routeIs('reports.*')) {
return $type;
}
$type = $request->get('type') ?: Str::singular((string) $request->segment(2));
if ($type == 'revenue') {
$type = 'income';
}
if ($type == 'payment') {
$type = 'expense';
}
return $type;
}
}