koel/app/Repositories/Repository.php

76 lines
2.1 KiB
PHP
Raw Normal View History

2018-08-29 13:15:11 +07:00
<?php
namespace App\Repositories;
use App\Repositories\Contracts\RepositoryInterface;
2018-08-29 13:15:11 +07:00
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Database\Eloquent\Model;
2022-07-27 17:32:36 +02:00
use Illuminate\Support\Collection;
2018-08-29 13:15:11 +07:00
2024-04-24 23:58:19 +02:00
/** @template T of Model */
2022-07-29 08:47:10 +02:00
abstract class Repository implements RepositoryInterface
2018-08-29 13:15:11 +07:00
{
2021-06-05 12:47:56 +02:00
private string $modelClass;
protected Guard $auth;
2024-06-08 20:15:24 +02:00
public Model $model;
2018-08-29 13:15:11 +07:00
2020-12-23 12:03:22 +01:00
public function __construct(?string $modelClass = null)
2018-08-29 13:15:11 +07:00
{
2020-12-23 12:03:22 +01:00
$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.
2022-08-08 18:00:59 +02:00
attempt(fn () => $this->auth = app(Guard::class), false);
2018-08-29 13:15:11 +07:00
}
2020-12-23 12:03:22 +01:00
private static function guessModelClass(): string
{
return preg_replace('/(.+)\\\\Repositories\\\\(.+)Repository$/m', '$1\Models\\\$2', static::class);
}
2024-04-24 23:58:19 +02:00
/** @return T */
public function getOne($id): Model
{
2024-04-24 23:58:19 +02:00
return $this->model::query()->findOrFail($id);
}
2024-05-19 13:49:42 +08:00
/** @return T|null */
public function findOneBy(array $params): ?Model
{
return $this->model::query()->where($params)->first();
}
2024-04-24 23:58:19 +02:00
/** @return T|null */
public function findOne($id): ?Model
2018-08-29 13:15:11 +07:00
{
2024-04-24 23:58:19 +02:00
return $this->model::query()->find($id);
2018-08-29 13:15:11 +07:00
}
2024-05-19 13:49:42 +08:00
/** @return T */
public function getOneBy(array $params): Model
{
return $this->model::query()->where($params)->firstOrFail();
}
2024-04-24 23:58:19 +02:00
/** @return array<array-key, T>|Collection<array-key, T> */
public function getMany(array $ids, bool $preserveOrder = false): Collection
2018-08-29 13:15:11 +07:00
{
$models = $this->model::query()->find($ids);
return $preserveOrder ? $models->orderByArray($ids) : $models;
2018-08-29 13:15:11 +07:00
}
2024-04-24 23:58:19 +02:00
/** @return array<array-key, T>|Collection<array-key, T> */
2018-08-29 13:15:11 +07:00
public function getAll(): Collection
{
2024-04-24 23:58:19 +02:00
return $this->model::all();
2018-08-29 13:15:11 +07:00
}
2020-09-06 20:21:39 +02:00
2024-04-24 23:58:19 +02:00
/** @return T|null */
2024-06-04 15:35:00 +02:00
public function findFirstWhere(...$params): ?Model
2020-09-06 20:21:39 +02:00
{
2024-04-24 23:58:19 +02:00
return $this->model::query()->firstWhere(...$params);
2020-12-24 13:41:18 +01:00
}
2018-08-29 13:15:11 +07:00
}