2018-08-29 06:15:11 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Repositories;
|
|
|
|
|
|
|
|
use Illuminate\Contracts\Auth\Guard;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
2022-07-27 15:32:36 +00:00
|
|
|
use Illuminate\Support\Collection;
|
2018-08-29 06:15:11 +00:00
|
|
|
|
2022-07-29 06:47:10 +00:00
|
|
|
abstract class Repository implements RepositoryInterface
|
2018-08-29 06:15:11 +00:00
|
|
|
{
|
2021-06-05 10:47:56 +00:00
|
|
|
private string $modelClass;
|
|
|
|
protected Model $model;
|
|
|
|
protected Guard $auth;
|
2018-08-29 06:15:11 +00:00
|
|
|
|
2020-12-23 11:03:22 +00:00
|
|
|
public function __construct(?string $modelClass = null)
|
2018-08-29 06:15:11 +00:00
|
|
|
{
|
2020-12-23 11:03:22 +00:00
|
|
|
$this->modelClass = $modelClass ?: self::guessModelClass();
|
|
|
|
$this->model = app($this->modelClass);
|
2019-01-01 11:53:20 +00:00
|
|
|
|
|
|
|
// This instantiation may fail during a console command if e.g. APP_KEY is empty,
|
|
|
|
// rendering the whole installation failing.
|
2022-08-08 16:00:59 +00:00
|
|
|
attempt(fn () => $this->auth = app(Guard::class), false);
|
2018-08-29 06:15:11 +00:00
|
|
|
}
|
|
|
|
|
2020-12-23 11:03:22 +00:00
|
|
|
private static function guessModelClass(): string
|
|
|
|
{
|
|
|
|
return preg_replace('/(.+)\\\\Repositories\\\\(.+)Repository$/m', '$1\Models\\\$2', static::class);
|
|
|
|
}
|
|
|
|
|
2018-08-29 06:15:11 +00:00
|
|
|
public function getOneById($id): ?Model
|
|
|
|
{
|
|
|
|
return $this->model->find($id);
|
|
|
|
}
|
|
|
|
|
2020-12-22 20:11:22 +00:00
|
|
|
/** @return Collection|array<Model> */
|
2018-08-29 06:15:11 +00:00
|
|
|
public function getByIds(array $ids): Collection
|
|
|
|
{
|
2021-06-05 10:47:56 +00:00
|
|
|
return $this->model->find($ids);
|
2018-08-29 06:15:11 +00:00
|
|
|
}
|
|
|
|
|
2020-12-22 20:11:22 +00:00
|
|
|
/** @return Collection|array<Model> */
|
2018-08-29 06:15:11 +00:00
|
|
|
public function getAll(): Collection
|
|
|
|
{
|
|
|
|
return $this->model->all();
|
|
|
|
}
|
2020-09-06 18:21:39 +00:00
|
|
|
|
2020-12-22 23:01:49 +00:00
|
|
|
public function getFirstWhere(...$params): ?Model
|
2020-09-06 18:21:39 +00:00
|
|
|
{
|
2021-06-05 10:47:56 +00:00
|
|
|
return $this->model->firstWhere(...$params);
|
2020-09-06 18:21:39 +00:00
|
|
|
}
|
2020-12-24 12:41:18 +00:00
|
|
|
|
|
|
|
public function getModelClass(): string
|
|
|
|
{
|
|
|
|
return $this->modelClass;
|
|
|
|
}
|
2018-08-29 06:15:11 +00:00
|
|
|
}
|