2018-08-29 06:15:11 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Repositories;
|
|
|
|
|
|
|
|
use Illuminate\Contracts\Auth\Guard;
|
2019-06-16 21:12:56 +00:00
|
|
|
use Illuminate\Database\Eloquent\Collection;
|
2018-08-29 06:15:11 +00:00
|
|
|
use Illuminate\Database\Eloquent\Model;
|
2020-12-22 20:11:22 +00:00
|
|
|
use Throwable;
|
2018-08-29 06:15:11 +00:00
|
|
|
|
|
|
|
abstract class AbstractRepository implements RepositoryInterface
|
|
|
|
{
|
2020-12-23 11:03:22 +00:00
|
|
|
/** @var string */
|
|
|
|
private $modelClass;
|
|
|
|
|
2018-08-29 06:15:11 +00:00
|
|
|
/** @var Model */
|
|
|
|
protected $model;
|
2019-01-01 11:53:34 +00:00
|
|
|
|
2019-01-01 11:53:20 +00:00
|
|
|
/** @var Guard */
|
2018-08-29 06:15:11 +00:00
|
|
|
protected $auth;
|
|
|
|
|
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.
|
|
|
|
try {
|
|
|
|
$this->auth = app(Guard::class);
|
2020-12-22 20:11:22 +00:00
|
|
|
} catch (Throwable $e) {
|
2019-01-01 11:53:34 +00:00
|
|
|
}
|
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
|
|
|
|
{
|
|
|
|
return $this->model->whereIn($this->model->getKeyName(), $ids)->get();
|
|
|
|
}
|
|
|
|
|
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
|
|
|
{
|
|
|
|
return $this->model->where(...$params)->first();
|
|
|
|
}
|
2018-08-29 06:15:11 +00:00
|
|
|
}
|