Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor repository contracts #1

Merged
merged 7 commits into from
Dec 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
},
"require-dev": {
"laravel/pint": "^1.8",
"nunomaduro/larastan": "^2.7",
"orchestra/testbench": "^8.0",
"phpstan/phpstan": "^1.10",
"phpunit/phpunit": "^9.0"
},
"autoload": {
Expand Down
4 changes: 2 additions & 2 deletions config/repository.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?php

return [
'perPage' => 20
];
'perPage' => 20,
];
5 changes: 4 additions & 1 deletion phpstan.neon.dist
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
includes:
- phpstan-baseline.neon
- ./vendor/nunomaduro/larastan/extension.neon

parameters:
level: 8
paths:
- src
- config
- config
checkMissingIterableValueType: false
checkGenericClassInNonGenericObjectType: false
97 changes: 62 additions & 35 deletions src/BaseEloquentRepository.php
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
<?php

namespace Salehhashemi\Repository;

use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Collection as GeneralCollection;
use Illuminate\Support\Collection;
use InvalidArgumentException;
use Salehhashemi\Repository\Contracts\CriteriaInterface;
use Salehhashemi\Repository\Contracts\RepositoryInterface;

Expand Down Expand Up @@ -36,6 +39,14 @@ public function __construct()
*/
abstract protected function getModelClass(): string;

/**
* This function returns the name of the field that will be used to display the record in the list view.
*/
protected function getDisplayField(): string
{
return 'id';
}

/**
* {@inheritDoc}
*/
Expand All @@ -47,7 +58,7 @@ public function findOne(int|string $primaryKey = null): ?Model

$this->applyCriteria();
$this->applyRelations();
$this->applyOrderBy();
$this->applyOrder();
$result = $this->getQuery()->first();
$this->resetQuery();

Expand All @@ -67,8 +78,8 @@ public function findOneOrFail(int|string $primaryKey = null): Model

if ($result === null) {
throw (new ModelNotFoundException())->setModel(
get_debug_type($this->model),
$primaryKey
$this->model::class,
$primaryKey ?? ''
);
}

Expand All @@ -78,7 +89,7 @@ public function findOneOrFail(int|string $primaryKey = null): Model
/**
* {@inheritDoc}
*/
public function findAll(array $options = []): Collection
public function findAll(array $options = []): EloquentCollection
{
$options += [
'limit' => null,
Expand All @@ -95,7 +106,7 @@ public function findAll(array $options = []): Collection

$this->applyCriteria();
$this->applyRelations();
$this->applyOrderBy();
$this->applyOrder();
$results = $this->getQuery()->get();
$this->resetQuery();

Expand All @@ -105,11 +116,11 @@ public function findAll(array $options = []): Collection
/**
* {@inheritDoc}
*/
public function findList(string $key = null, string $value = null): GeneralCollection
public function findList(string $key = null, string $value = null): Collection
{
$this->applyCriteria();
$this->applyRelations();
$this->applyOrderBy();
$this->applyOrder();

$key = $key ?? $this->getModel()->getKeyName();
$value = $value ?? $this->getDisplayField();
Expand All @@ -129,22 +140,35 @@ public function findList(string $key = null, string $value = null): GeneralColle
*/
public function paginate(int $perPage = null): Paginator
{
$this->perPage = $perPage ?? $this->perPage;
$perPage = $this->preparePageSize($perPage);

$this->applyCriteria();
$this->applyRelations();
$this->applyOrderBy();
$this->applyOrder();
$results = $this->getQuery()->paginate($perPage);
$this->resetQuery();

return $results;
}

/**
* @param array $conditions Conditions
* @return $this
* Prepare the page size for pagination.
*
* @throws \InvalidArgumentException
*/
protected function applyConditions(array $conditions): self
protected function preparePageSize(int $perPage = null): int
{
if ($perPage <= 0) {
throw new InvalidArgumentException('Invalid page size');
}

return min($perPage, $this->perPage);
}

/**
* Apply conditions to the query based on an array of conditions.
*/
protected function applyConditions(array $conditions): static
{
$conditions = array_combine($this->aliasFields(array_keys($conditions)), $conditions);
$this->getQuery()->where($conditions);
Expand All @@ -155,17 +179,17 @@ protected function applyConditions(array $conditions): self
/**
* {@inheritDoc}
*/
public function addCriteria(CriteriaInterface $criteria): self
public function addCriteria(CriteriaInterface $criteria): static
{
$this->criteria[] = $criteria;

return $this;
}

/**
* @return $this
* Apply criteria to the query based on registered criteria objects.
*/
protected function applyCriteria(): self
protected function applyCriteria(): static
{
foreach ($this->criteria as $criteria) {
$criteria->apply($this->getModel(), $this->getQuery());
Expand All @@ -177,14 +201,17 @@ protected function applyCriteria(): self
/**
* {@inheritDoc}
*/
public function orderBy(string $field, string $direction = 'ASC'): self
public function orderBy(string $field, string $direction = 'ASC'): static
{
$this->orderByFields[$this->aliasField($field)] = $direction;

return $this;
}

protected function applyOrderBy(): void
/**
* Apply ordering to the query based on specified fields and directions.
*/
protected function applyOrder(): static
{
$fields = $this->orderByFields;
if (! $fields) {
Expand All @@ -194,13 +221,14 @@ protected function applyOrderBy(): void
foreach ($fields as $field => $direction) {
$this->getQuery()->orderBy($field, $direction);
}

return $this;
}

/**
* @param array $relations Relations
* @return $this
* Add relations to be eager-loaded when querying.
*/
protected function with(array $relations): self
protected function with(array $relations): static
{
$this->relations = array_merge($this->relations, $relations);

Expand All @@ -210,7 +238,7 @@ protected function with(array $relations): self
/**
* {@inheritDoc}
*/
public function lockForUpdate(): self
public function lockForUpdate(): static
{
$this->getQuery()->lockForUpdate();

Expand All @@ -220,18 +248,23 @@ public function lockForUpdate(): self
/**
* {@inheritDoc}
*/
public function sharedLock(): self
public function sharedLock(): static
{
$this->getQuery()->sharedLock();

return $this;
}

protected function applyRelations(): void
/**
* Apply eager-loading relations to the query.
*/
protected function applyRelations(): static
{
if ($this->relations) {
$this->getQuery()->with($this->relations);
}

return $this;
}

/**
Expand Down Expand Up @@ -266,8 +299,7 @@ protected function aliasField(string $field): string
protected function getModel(): Model
{
if (! isset($this->model)) {
$className = $this->getModelClass();
$this->model = new $className();
$this->model = app($this->getModelClass());
}

return $this->model;
Expand Down Expand Up @@ -301,19 +333,14 @@ protected function getQuery(): Builder
return $this->query;
}

/**
* Reset the query builder and related properties.
*/
protected function resetQuery(): void
{
unset($this->query);
$this->criteria = [];
$this->relations = [];
$this->orderByFields = [];
}

/**
* This function returns the name of the field that will be used to display the record in the list view.
*/
protected function getDisplayField(): string
{
return 'id';
}
}
5 changes: 4 additions & 1 deletion src/BaseFilter.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

namespace Salehhashemi\Repository;

use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Illuminate\Database\Eloquent\Model;

Expand Down Expand Up @@ -36,6 +38,7 @@ protected function whereLike(string $field, string $value, int $type): self
$this::WILD_BEFORE => '%'.$value,
$this::WILD_AFTER => $value.'%',
$this::WILD_BOTH => '%'.$value.'%',
default => $value,
};

$this->getQuery()->where($field, 'like', $matchText);
Expand Down Expand Up @@ -84,4 +87,4 @@ protected function getQuery(): QueryBuilder

return $this->builder;
}
}
}
7 changes: 3 additions & 4 deletions src/Contracts/CriteriaInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@

namespace Salehhashemi\Repository\Contracts;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Contracts\Database\Query\Builder;
use Illuminate\Database\Eloquent\Model;

interface CriteriaInterface
{
/**
* @param \Illuminate\Database\Eloquent\Model $model Model
* @param \Illuminate\Database\Eloquent\Builder $query Query
* Apply the criteria to the given Eloquent query builder.
*/
public function apply(Model $model, Builder $query): Builder;
}
}
Loading