Skip to content

Commit 2cf6397

Browse files
author
Admin
committed
Add Request::getFiltered(string $key, mixed $default = null, string|int $filter = '', array|int $options= []) macro
1 parent c5ed1f8 commit 2cf6397

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

src/Providers/CrudProvider.php

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@
66
use Illuminate\Database\Eloquent\Model;
77
use Illuminate\Database\Eloquent\Relations\Relation;
88
use Illuminate\Http\Request;
9+
use Illuminate\Support\Facades\Log;
910
use Illuminate\Support\ServiceProvider;
1011
use MacropaySolutions\LaravelCrudWizard\Models\BaseModel;
12+
use Symfony\Component\HttpFoundation\ParameterBag;
1113

1214
class CrudProvider extends ServiceProvider
1315
{
@@ -68,6 +70,66 @@ function (...$arguments): Model {
6870
return $this;
6971
});
7072

73+
Request::macro(
74+
'getFiltered',
75+
/**
76+
* @param string|int $filter can be 'alpha', 'alnum', 'digits', 'int', 'boolean' or an int flag
77+
* @see \filter_var() for $filter and $options
78+
* @see ParameterBag::getAlpha()
79+
* @see ParameterBag::getAlnum()
80+
* @see ParameterBag::getDigits()
81+
* @see ParameterBag::getInt()
82+
* @see ParameterBag::getBoolean()
83+
*/
84+
function (
85+
string $key,
86+
mixed $default = null,
87+
string|int $filter = '',
88+
array|int $options = [],
89+
): mixed {
90+
/** @var Request $this */
91+
if (\is_int($filter)) {
92+
if ($this->attributes->has($key)) {
93+
return $this->attributes->filter($key, $default, $filter, $options);
94+
}
95+
96+
if ($this->query->has($key)) {
97+
return $this->query->filter($key, $default, $filter, $options);
98+
}
99+
100+
if ($this->request->has($key)) {
101+
return $this->request->filter($key, $default, $filter, $options);
102+
}
103+
104+
return $default;
105+
}
106+
107+
if ($filter !== '') {
108+
$filter = \ucfirst(\strtolower($filter));
109+
110+
if (!\in_array($filter, ['Alpha', 'Alnum', 'Digits', 'Int', 'Boolean'], true)) {
111+
$filter = '';
112+
}
113+
}
114+
115+
try {
116+
if ($this->attributes->has($key)) {
117+
return $this->attributes->{'get' . $filter}($key, $default);
118+
}
119+
if ($this->query->has($key)) {
120+
return $this->query->{'get' . $filter}($key, $default);
121+
}
122+
if ($this->request->has($key)) {
123+
return $this->request->{'get' . $filter}($key, $default);
124+
}
125+
} catch (\Throwable $e) {
126+
Log::error($e->getMessage(), $e->getTrace());
127+
}
128+
129+
return $default;
130+
}
131+
);
132+
71133
Relation::macro('noConstraintsForRelationName', function (?string $relation = null): ?string {
72134
global $noConstraintsForRelationName;
73135

0 commit comments

Comments
 (0)