-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRepository.php
63 lines (50 loc) · 1.65 KB
/
Repository.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
<?php
namespace App\Repositories;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
abstract class Repository implements RepositoryInterface
{
private string $modelClass;
protected Model $model;
protected Guard $auth;
public function __construct(?string $modelClass = null)
{
$this->modelClass = $modelClass ?: self::guessModelClass();
$this->model = app($this->modelClass);
// This instantiation may fail during a console command if e.g. APP_KEY is empty,
// rendering the whole installation failing.
attempt(fn () => $this->auth = app(Guard::class), false);
}
private static function guessModelClass(): string
{
return preg_replace('/(.+)\\\\Repositories\\\\(.+)Repository$/m', '$1\Models\\\$2', static::class);
}
public function getOne($id): Model
{
return $this->model->findOrFail($id);
}
public function findOne($id): ?Model
{
return $this->model->find($id);
}
/** @return Collection|array<array-key, Model> */
public function getMany(array $ids, bool $inThatOrder = false): Collection
{
$models = $this->model::query()->find($ids);
return $inThatOrder ? $models->orderByArray($ids) : $models;
}
/** @return Collection|array<array-key, Model> */
public function getAll(): Collection
{
return $this->model->all();
}
public function getFirstWhere(...$params): ?Model
{
return $this->model->firstWhere(...$params);
}
public function getModelClass(): string
{
return $this->modelClass;
}
}