File size: 2,099 Bytes
89a1081 | 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 | <?php
namespace App\Service\Admin\Core;
use App\Enums\StatusEnum;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
class CollectionService extends Collection
{
public function collectionSearch(array $params, bool $like = true) {
$search = request()->input("search");
if (!$search) {
return $this;
}
$search = $like ? "%$search%" : $search;
return $this->filter(function ($item, $key) use ($params, $search, $like) {
if ($this->matches($key, $search, $like)) {
return true;
}
foreach ($params as $param) {
if ($this->matches($item[$param] ?? null, $search, $like)) {
return true;
}
}
return false;
});
}
private function matches($value, $search, $like) {
if (is_null($value)) {
return false;
}
if ($like) {
return stripos($value, trim($search, '%')) !== false;
} else {
return $value == $search;
}
}
public function paginate($perPage = null, $page = null, $options = []) {
$page = $page ?: (LengthAwarePaginator::resolveCurrentPage() ?: 1);
$items = $this->forPage($page, $perPage);
return new LengthAwarePaginator($items, $this->count(), $perPage, $page, $options);
}
public function keyFilter($route, $value = null, $key = 'status') {
if($route == 'index') {
return $this;
} else {
return $this->filter(function ($item) use ($key, $value, $route) {
if($route == 'active') {
return $item[$key] == StatusEnum::TRUE->status();
} elseif($route == 'inactive') {
return $item[$key] == StatusEnum::FALSE->status();
} else {
return $item[$key] == $value;
}
});
}
}
}
|