├── workbench ├── database │ ├── factories │ │ ├── .gitkeep │ │ └── UserFactory.php │ └── seeders │ │ ├── .gitkeep │ │ └── DatabaseSeeder.php └── app │ ├── Repositories │ └── UserRepository.php │ ├── Providers │ └── WorkbenchServiceProvider.php │ └── Models │ └── User.php ├── src ├── Eloquent │ ├── DefaultRepository.php │ └── AbstractRepository.php ├── Exceptions │ ├── ClassException.php │ ├── NoResultsFoundException.php │ ├── ClassNotFoundException.php │ └── RepositoryIntegrityException.php ├── Contracts │ ├── HookInterface.php │ ├── CriteriaInterface.php │ └── RepositoryInterface.php ├── Commands │ ├── Generators │ │ ├── HookMakeCommand.php │ │ ├── CriteriaMakeCommand.php │ │ ├── RepositoryInterfaceMakeCommand.php │ │ ├── EloquentRepositoryMakeCommand.php │ │ └── RepositoryMakeCommand.php │ └── InstallCommand.php ├── Facades │ └── Repository.php ├── Concerns │ ├── BootsTraits.php │ ├── RemembersWhatHappened.php │ ├── CRUD │ │ ├── HasUpdateOperations.php │ │ ├── HasCreateOperations.php │ │ ├── HasDeleteOperations.php │ │ └── HasReadOperations.php │ ├── InteractsWithModel.php │ ├── HasEvents.php │ └── Criteria │ │ └── AppliesCriteria.php ├── Providers │ ├── EventServiceProvider.php │ └── RepositoryServiceProvider.php ├── Criteria │ └── AnonymousCriteria.php ├── Events │ └── MemoryFragment.php ├── Attributes │ └── Repository.php └── Managers │ └── RepositoryManager.php ├── stubs ├── repository.interface.stub ├── criteria.stub ├── repository.eloquent.stub └── hook.stub ├── phpstan.dist.neon ├── config └── repository.php ├── LICENCE.md ├── README.md └── composer.json /workbench/database/factories/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /workbench/database/seeders/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/Eloquent/DefaultRepository.php: -------------------------------------------------------------------------------- 1 | model}", 404); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /stubs/criteria.stub: -------------------------------------------------------------------------------- 1 | Trovee\Repository\Eloquent\DefaultRepository::class, 6 | 7 | 'should_be_strict' => true, 8 | 9 | 'history' => [ 10 | 'enabled' => true, 11 | 'max_event_to_remember' => 10, 12 | ], 13 | 14 | 'bindings' => [ 15 | // App\Repositories\UserRepository::class => App\Repositories\Eloquent\UserRepository::class // or 'default', 16 | ], 17 | 18 | ]; 19 | -------------------------------------------------------------------------------- /src/Commands/Generators/HookMakeCommand.php: -------------------------------------------------------------------------------- 1 | {$method}(); 18 | $booted[] = $method; 19 | $this->trigger('boot:trait:'.$trait); 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /workbench/app/Providers/WorkbenchServiceProvider.php: -------------------------------------------------------------------------------- 1 | set('repository.bindings'.UserRepository::class, 'default'); 25 | Route::view('/', 'welcome'); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Commands/Generators/CriteriaMakeCommand.php: -------------------------------------------------------------------------------- 1 | 11 | */ 12 | protected array $listen = [ 13 | 14 | ]; 15 | 16 | public function boot(): void 17 | { 18 | foreach ($this->listen as $event => $listeners) { 19 | foreach ($listeners as $listener) { 20 | $this->app['events']->listen($event, $listener); 21 | } 22 | } 23 | } 24 | 25 | public function listens(): array 26 | { 27 | return $this->listen; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Commands/Generators/RepositoryInterfaceMakeCommand.php: -------------------------------------------------------------------------------- 1 | closure = $closure instanceof Closure 17 | ? new SerializableClosure($closure) 18 | : $closure; 19 | } 20 | 21 | public function apply(Builder $query): Builder 22 | { 23 | return $this->closure->getClosure()($query, ...$this->args); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Commands/InstallCommand.php: -------------------------------------------------------------------------------- 1 | components->info('Installing Trovee Repository package...'); 18 | 19 | $this->call('vendor:publish', [ 20 | '--provider' => RepositoryServiceProvider::class, 21 | '--tag' => 'repository-config', 22 | ] + ($this->getOptions())); 23 | 24 | $this->components->info('Trovee Repository package installed successfully.'); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Events/MemoryFragment.php: -------------------------------------------------------------------------------- 1 | timestamp = $timestamp ?? microtime(true); 15 | } 16 | 17 | public function toArray() 18 | { 19 | return [ 20 | 'event' => $this->event, 21 | 'data' => $this->data, 22 | ]; 23 | } 24 | 25 | public function getEvent(): string 26 | { 27 | return $this->event; 28 | } 29 | 30 | public function setEvent(string $event): MemoryFragment 31 | { 32 | $this->event = $event; 33 | 34 | return $this; 35 | } 36 | 37 | public function getData(): mixed 38 | { 39 | return $this->data; 40 | } 41 | 42 | public function setData(mixed $data): MemoryFragment 43 | { 44 | $this->data = $data; 45 | 46 | return $this; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /LICENCE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) Trovee 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![](https://raw.githubusercontent.com/trovee/laravel-repository/main/.github/art/banner.png) 2 | 3 | # Laravel Repository 4 | 5 | An up to date repository pattern implementation for Laravel 10+. 6 | 7 | ## Installation 8 | 9 | You can install the package via composer: 10 | 11 | ```bash 12 | composer require trovee/laravel-repository 13 | ``` 14 | 15 | After installing the package, you need to trigger the installation command: 16 | 17 | ```bash 18 | php artisan repository:install 19 | ``` 20 | 21 | ## Documentation 22 | 23 | You can find detailed documentation in the GitHub pages of the 24 | project. [Documentation](https://trovee.github.io/laravel-repository/) 25 | 26 | ## License 27 | 28 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 29 | 30 | ## Contributing & Support 31 | 32 | All contributions are welcome and encouraged. Please create an issue or submit a pull request if you have any ideas or 33 | suggestions. Thanks to all contributors, you make this project possible! Here is a list of our top contributors: 34 | 35 | - [@uutkukorkmaz](https://github.com/uutkukorkmaz) 36 | - [All Contributors](https://github.com/trovee/laravel-repository/graphs/contributors) 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /workbench/app/Models/User.php: -------------------------------------------------------------------------------- 1 | 21 | */ 22 | protected $fillable = [ 23 | 'name', 24 | 'email', 25 | 'password', 26 | ]; 27 | 28 | /** 29 | * The attributes that should be hidden for serialization. 30 | * 31 | * @var array 32 | */ 33 | protected $hidden = [ 34 | 'password', 35 | 'remember_token', 36 | ]; 37 | 38 | /** 39 | * The attributes that should be cast. 40 | * 41 | * @var array 42 | */ 43 | protected $casts = [ 44 | 'email_verified_at' => 'datetime', 45 | 'password' => 'hashed', 46 | ]; 47 | } 48 | -------------------------------------------------------------------------------- /workbench/database/factories/UserFactory.php: -------------------------------------------------------------------------------- 1 | 12 | */ 13 | class UserFactory extends Factory 14 | { 15 | /** 16 | * The current password being used by the factory. 17 | */ 18 | protected static ?string $password; 19 | 20 | public function modelName() 21 | { 22 | return User::class; 23 | } 24 | 25 | /** 26 | * Define the model's default state. 27 | * 28 | * @return array 29 | */ 30 | public function definition(): array 31 | { 32 | return [ 33 | 'name' => fake()->name(), 34 | 'email' => fake()->unique()->safeEmail(), 35 | 'email_verified_at' => now(), 36 | 'password' => static::$password ??= Hash::make('password'), 37 | 'remember_token' => Str::random(10), 38 | ]; 39 | } 40 | 41 | /** 42 | * Indicate that the model's email address should be unverified. 43 | */ 44 | public function unverified(): static 45 | { 46 | return $this->state(fn (array $attributes) => [ 47 | 'email_verified_at' => null, 48 | ]); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Attributes/Repository.php: -------------------------------------------------------------------------------- 1 | validateRepository(); 22 | 23 | try { 24 | return app($this->repositoryFqcn)->proxyOf($target); 25 | } catch (BindingResolutionException) { 26 | return RepositoryFacade::getDefaultRepositoryAsTargetedToModel($target); 27 | } 28 | } 29 | 30 | protected function validateRepository(): void 31 | { 32 | $exception = match (true) { 33 | ! interface_exists($this->repositoryFqcn) => new ClassNotFoundException($this->repositoryFqcn), 34 | ! is_subclass_of($this->repositoryFqcn, RepositoryInterface::class) => new RepositoryIntegrityException( 35 | action: 'validate', 36 | fqcn: $this->repositoryFqcn, 37 | verb: 'implements', 38 | inheritance: RepositoryInterface::class 39 | ), 40 | default => null, 41 | }; 42 | 43 | if (! is_null($exception)) { 44 | throw $exception; 45 | } 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/Concerns/RemembersWhatHappened.php: -------------------------------------------------------------------------------- 1 | isHistoryEnabled()) { 15 | return; 16 | } 17 | 18 | $this->history = new Collection(); 19 | } 20 | 21 | public function remember(string $event, mixed $data): void 22 | { 23 | if (! $this->isHistoryEnabled()) { 24 | return; 25 | } 26 | 27 | $this->optimizeMemory(); 28 | 29 | $this->history->push(new MemoryFragment($event, $data)); 30 | } 31 | 32 | public function isHappened(string $event): bool 33 | { 34 | if (! $this->isHistoryEnabled()) { 35 | return false; 36 | } 37 | 38 | return $this->history->contains('event', $event); 39 | } 40 | 41 | public function isHistoryEnabled(): bool 42 | { 43 | return config('repository.history.enabled'); 44 | } 45 | 46 | public function optimizeMemory(): void 47 | { 48 | if (! isset($this->history)) { 49 | $this->history = new Collection(); 50 | } 51 | 52 | if ($this->history->count() <= config('repository.history.max_event_to_remember')) { 53 | return; 54 | } 55 | /** @var MemoryFragment $oldest */ 56 | $oldest = $this->history->first(); 57 | if ($oldest->getEvent() !== 'boot') { 58 | $this->history->shift(); 59 | 60 | return; 61 | } 62 | 63 | $this->history->splice(1, 1); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Concerns/CRUD/HasUpdateOperations.php: -------------------------------------------------------------------------------- 1 | result) && $this->result instanceof Model) { 14 | return $this->result; 15 | } 16 | 17 | if (isset($this->record)) { 18 | return $this->record; 19 | } 20 | 21 | throw new \LogicException( 22 | 'Failed to call update() method. '.static::class.' needs to know which record to update.' 23 | ); 24 | } 25 | 26 | public function update(array $data): ?Model 27 | { 28 | $data = $this->filterFillable($data); 29 | 30 | $updatable = $this->getUpdatable(); 31 | 32 | $this->trigger('updating', $old = $updatable->toArray(), $data); 33 | $updated = $this->getRecord()->update($data); 34 | 35 | if (! $updated) { 36 | $this->trigger('update:failed', $old, $data); 37 | 38 | return null; 39 | } 40 | 41 | $this->trigger('update:success', $old, $data); 42 | 43 | $this->setRecord($this->getRecord()->fresh()); 44 | 45 | return $this->record; 46 | } 47 | 48 | public function updateThenReturn(array $data): RepositoryInterface 49 | { 50 | $this->update($data); 51 | 52 | return $this; 53 | } 54 | 55 | public function findAndUpdate(array $attributes, array $data): ?Model 56 | { 57 | $updatable = $this->firstOrFailByAttributes($attributes); 58 | 59 | $this->setResult($updatable); 60 | 61 | return $this->update($data); 62 | } 63 | 64 | public function updateFromRequest(FormRequest $request): ?Model 65 | { 66 | return $this->update($request->validated()); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/Concerns/CRUD/HasCreateOperations.php: -------------------------------------------------------------------------------- 1 | detectMultiLevelArray($data)) { 15 | return $this->createMany($data); 16 | } 17 | 18 | $data = $this->filterFillable($data); 19 | 20 | $this->trigger('creating', $data); 21 | $newRecord = $this->createNewQueryBuilder()->create($data); 22 | $this->setRecord($newRecord); 23 | $this->trigger('created', $data); 24 | 25 | return $this->record; 26 | } 27 | 28 | public function createFromRequest(FormRequest $request): Model 29 | { 30 | return $this->create($request->validated()); 31 | } 32 | 33 | public function firstOrCreate(array $search, array $create): Model 34 | { 35 | $this->setResult( 36 | $this->createNewQueryBuilder()->firstOrCreate($search, $create) 37 | ); 38 | 39 | return $this->result; 40 | } 41 | 42 | public function updateOrCreate(array $search, array $update): Model 43 | { 44 | $this->setResult($this->createNewQueryBuilder()->updateOrCreate($search, $update)); 45 | 46 | return $this->result; 47 | } 48 | 49 | public function createThenReturn(array $data): RepositoryInterface 50 | { 51 | $this->create($data); 52 | 53 | return $this; 54 | } 55 | 56 | public function createMany(array $data): Collection 57 | { 58 | $records = []; 59 | foreach ($data as $item) { 60 | $records[] = $this->create($item); 61 | } 62 | 63 | $this->setResult(new Collection($records)); 64 | 65 | return $this->result; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/Providers/RepositoryServiceProvider.php: -------------------------------------------------------------------------------- 1 | publishes([ 15 | __DIR__.'/../../config/repository.php' => config_path('repository.php'), 16 | ], 'repository-config'); 17 | 18 | $this->mergeConfigFrom( 19 | __DIR__.'/../../config/repository.php', 20 | 'repository' 21 | ); 22 | 23 | $this->commands([ 24 | Commands\InstallCommand::class, 25 | Commands\Generators\RepositoryMakeCommand::class, 26 | Commands\Generators\CriteriaMakeCommand::class, 27 | Commands\Generators\HookMakeCommand::class, 28 | ]); 29 | } 30 | 31 | public function boot(): void 32 | { 33 | $this->handleBindings(); 34 | 35 | Model::preventLazyLoading( 36 | config('repository.should_be_strict', Model::preventsLazyLoading()) 37 | ); 38 | Model::preventAccessingMissingAttributes( 39 | config('repository.should_be_strict', Model::preventsAccessingMissingAttributes()) 40 | ); 41 | Model::preventSilentlyDiscardingAttributes( 42 | config('repository.should_be_strict', Model::preventsSilentlyDiscardingAttributes()) 43 | ); 44 | 45 | } 46 | 47 | protected function handleBindings(): void 48 | { 49 | $this->app->bind('repository.registry', fn ($app) => $app->make(RepositoryManager::class)); 50 | 51 | foreach (config('repository.bindings') as $abstract => $concrete) { 52 | if ($concrete === 'default') { 53 | continue; 54 | } 55 | $this->app->bind($abstract, $concrete); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/Commands/Generators/EloquentRepositoryMakeCommand.php: -------------------------------------------------------------------------------- 1 | files->get($this->getStub()); 30 | 31 | return $this->replaceNamespace($stub, $name) 32 | ->replaceModel($stub, $name) 33 | ->replaceInterface($stub, $name) 34 | ->replaceClass($stub, $name); 35 | } 36 | 37 | protected function replaceInterface(&$stub, $name) 38 | { 39 | $interface = str_replace('Eloquent\\', 'Contracts\\', $name).'Contract'; 40 | $interfaceShortName = class_basename($interface); 41 | $stub = str_replace('{{ interface }}', $interface, $stub); 42 | $stub = str_replace('{{ interfaceShortName }}', $interfaceShortName, $stub); 43 | 44 | return $this; 45 | } 46 | 47 | protected function replaceModel(&$stub, $name) 48 | { 49 | $model = $this->guessModel($name); 50 | $modelShortName = class_basename($model); 51 | $stub = str_replace('{{ model }}', $model, $stub); 52 | $stub = str_replace('{{ modelShortName }}', $modelShortName, $stub); 53 | 54 | return $this; 55 | } 56 | 57 | protected function guessModel($name) 58 | { 59 | $root = trim($this->rootNamespace(), '\\'); 60 | 61 | return Str::replace([$this->getDefaultNamespace($root), 'Repository'], ['App\Models', ''], $name); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/Concerns/CRUD/HasDeleteOperations.php: -------------------------------------------------------------------------------- 1 | getModelInstance())); 13 | } 14 | 15 | public function delete(?Model $model = null): bool 16 | { 17 | if (! is_null($model)) { 18 | $this->setRecord($model); 19 | } 20 | 21 | $this->trigger('deleting', $record = $this->getRecord()); 22 | 23 | $result = $this->modelUsingSoftDeletes() 24 | ? $record->delete() 25 | : $this->forceDelete(); 26 | 27 | $this->trigger('deleted', $this->getRecord()); 28 | 29 | return $result; 30 | } 31 | 32 | public function forceDelete(?Model $model = null): bool 33 | { 34 | if (! is_null($model)) { 35 | $this->setRecord($model); 36 | } 37 | 38 | $this->trigger('force_deleting', $record = $this->getRecord()); 39 | 40 | $result = $record->forceDelete(); 41 | 42 | $this->trigger('force_deleted', $record); 43 | 44 | return $result; 45 | } 46 | 47 | public function deleteThenReturn(?Model $model = null): self 48 | { 49 | $this->delete($model); 50 | 51 | return $this; 52 | } 53 | 54 | /** 55 | * @return int Number of deleted records 56 | */ 57 | public function deleteAllDuplicates(array $attributes): int 58 | { 59 | $this->trigger('deleting_duplicates', $attributes); 60 | 61 | $result = $this->createNewQueryBuilder() 62 | ->where($attributes) 63 | ->delete(); 64 | 65 | $this->trigger('deleted_duplicates', $attributes); 66 | 67 | return $result; 68 | } 69 | 70 | /** 71 | * @return int Number of deleted records 72 | */ 73 | public function deleteDuplicatesAndKeepOne(array $attributes): int 74 | { 75 | $this->trigger('deleting_duplicates_and_keeping_one', $attributes); 76 | 77 | $result = $this->createNewQueryBuilder() 78 | ->where($attributes) 79 | ->orderBy('id', 'desc') 80 | ->offset(1) 81 | ->delete(); 82 | 83 | $this->trigger('deleted_duplicates_and_kept_one', $attributes); 84 | 85 | return $result; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/Concerns/CRUD/HasReadOperations.php: -------------------------------------------------------------------------------- 1 | applyCriteria(); 14 | $this->where($attributes); 15 | 16 | $this->trigger('op:read:getByAttributes', $attributes); 17 | 18 | $this->setResult($this->getBuilder()->get()); 19 | 20 | return $this->result; 21 | } 22 | 23 | public function getOrFailByAttributes(array $attributes): Collection 24 | { 25 | $result = $this->getByAttributes($attributes); 26 | 27 | if ($result->isEmpty()) { 28 | throw new NoResultsFoundException($this->model); 29 | } 30 | 31 | $this->trigger('op:read:getOrFailByAttributes', $attributes); 32 | $this->setResult($result); 33 | 34 | return $this->result; 35 | } 36 | 37 | public function firstByAttributes(array $attributes): ?Model 38 | { 39 | $this->applyCriteria(); 40 | $this->where($attributes); 41 | 42 | $this->trigger('op:read:firstByAttributes', $attributes); 43 | $this->setResult($this->getBuilder()->first()); 44 | 45 | return $this->result; 46 | } 47 | 48 | public function firstOrFailByAttributes(array $attributes): Model 49 | { 50 | $result = $this->firstByAttributes($attributes); 51 | 52 | if (is_null($result)) { 53 | throw new NoResultsFoundException($this->model); 54 | } 55 | 56 | $this->trigger('op:read:firstOrFailByAttributes', $attributes); 57 | $this->setResult($result); 58 | 59 | return $this->result; 60 | } 61 | 62 | public function all(): Collection 63 | { 64 | $this->applyCriteria(); 65 | 66 | $this->trigger('op:read:all'); 67 | 68 | $this->setResult($this->getBuilder()->get()); 69 | 70 | return $this->result; 71 | } 72 | 73 | public function first(): ?Model 74 | { 75 | $this->applyCriteria(); 76 | 77 | $this->trigger('op:read:first'); 78 | $this->setResult($this->getBuilder()->first()); 79 | 80 | return $this->result; 81 | } 82 | 83 | public function firstOrFail(): Model 84 | { 85 | $this->trigger('op:read:firstOrFail'); 86 | 87 | return $this->firstOrFailByAttributes([]); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/Concerns/InteractsWithModel.php: -------------------------------------------------------------------------------- 1 | record)) { 19 | return $this->record; 20 | } 21 | 22 | return app()->make($this->model); 23 | } 24 | 25 | public function setRecord(Model $record): RepositoryInterface 26 | { 27 | $this->record = $record; 28 | 29 | return $this; 30 | } 31 | 32 | public function setResult(Model|Collection $result): RepositoryInterface 33 | { 34 | $this->result = $result; 35 | 36 | return $this; 37 | } 38 | 39 | public function getRecord(): Model 40 | { 41 | if (! isset($this->record)) { 42 | if (isset($this->result) && $this->result instanceof Model) { 43 | $this->setRecord($this->result); 44 | 45 | return $this->record; 46 | } 47 | 48 | throw new \LogicException( 49 | 'Failed to call getRecord() method. '.static::class.' needs to know which record to get.' 50 | ); 51 | } 52 | 53 | return $this->record; 54 | } 55 | 56 | public function getResult(): Model|Collection 57 | { 58 | return $this->result; 59 | } 60 | 61 | public function createNewQueryBuilder(): Builder 62 | { 63 | $this->query = $this->getModelInstance()->newQuery(); 64 | 65 | return $this->query; 66 | } 67 | 68 | public function getFillable(): array 69 | { 70 | return $this->getModelInstance()->getFillable(); 71 | } 72 | 73 | public function filterFillable(array $data): array 74 | { 75 | return collect($data)->only($this->getFillable())->toArray(); 76 | } 77 | 78 | public function getTable(): string 79 | { 80 | return $this->getModelInstance()->getTable(); 81 | } 82 | 83 | public function getKeyName(): string 84 | { 85 | return $this->getModelInstance()->getKeyName(); 86 | } 87 | 88 | public function getQualifiedKeyName(): string 89 | { 90 | return $this->getModelInstance()->qualifyColumn($this->getKeyName()); 91 | } 92 | 93 | public function getKey(): mixed 94 | { 95 | return $this->getModelInstance()->getKey(); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/Concerns/HasEvents.php: -------------------------------------------------------------------------------- 1 | > 15 | */ 16 | protected array $hooks = []; 17 | 18 | protected function trigger(string $hook, ...$args): void 19 | { 20 | $this->triggerSelfRegistryHooks($hook, ...$args); 21 | 22 | $this->triggerMethodHook($hook, $args); 23 | 24 | $this->triggerClassHook($hook, ...$args); 25 | 26 | $this->remember($hook, $args); 27 | 28 | } 29 | 30 | private function triggerMethodHook(string $hook, array $args): void 31 | { 32 | $hookMethod = 'on'.Str::studly($hook); 33 | 34 | if (method_exists($this, $hookMethod)) { 35 | $this->{$hookMethod}(...$args); 36 | } 37 | } 38 | 39 | private function triggerClassHook(string $hook, ...$args): void 40 | { 41 | if (class_exists($hook)) { 42 | $instance = app()->make($hook, ['repository' => $this, ...$args]); 43 | 44 | if (! ($instance instanceof HookInterface)) { 45 | throw new RepositoryIntegrityException( 46 | action: 'trigger hook', 47 | fqcn: $hook, 48 | verb: 'implement', 49 | inheritance: HookInterface::class 50 | ); 51 | } 52 | 53 | $instance->onTrigger($this, ...$args); 54 | } 55 | } 56 | 57 | private function triggerSelfRegistryHooks(string $hook, ...$args): void 58 | { 59 | foreach ($this->getTriggerableHooks($hook) as $listener) { 60 | $this->triggerClassHook($listener, ...$args); 61 | } 62 | } 63 | 64 | public function addHook(string $hook, string|Closure $fqcn): RepositoryInterface 65 | { 66 | $this->hooks[$hook][] = $fqcn; 67 | 68 | return $this; 69 | } 70 | 71 | public function addHooks(array $hooks): RepositoryInterface 72 | { 73 | foreach ($hooks as $hook => $listeners) { 74 | foreach ($listeners as $fqcn) { 75 | $this->addHook($hook, $fqcn); 76 | } 77 | } 78 | 79 | return $this; 80 | } 81 | 82 | public function getTriggerableHooks(?string $hook = null): array 83 | { 84 | return $this->hooks[$hook] ?? []; 85 | } 86 | 87 | public function getHooks(): array 88 | { 89 | return $this->hooks; 90 | } 91 | 92 | protected function dispatchEvent(string $event, ...$args): void 93 | { 94 | $args['repository'] = $this; 95 | 96 | event($event, $args); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "trovee/laravel-repository", 3 | "description": "An up to date repository pattern implementation for Laravel", 4 | "type": "library", 5 | "license": "MIT", 6 | "autoload": { 7 | "psr-4": { 8 | "Trovee\\Repository\\": "src/" 9 | } 10 | }, 11 | "autoload-dev": { 12 | "psr-4": { 13 | "Trovee\\Repository\\Tests\\": "tests/", 14 | "Workbench\\App\\": "workbench/app/", 15 | "Workbench\\Database\\Factories\\": "workbench/database/factories/", 16 | "Workbench\\Database\\Seeders\\": "workbench/database/seeders/" 17 | } 18 | }, 19 | "minimum-stability": "stable", 20 | "require": { 21 | "php": "^8.1", 22 | "illuminate/contracts": "^10.48", 23 | "illuminate/database": "^10.48", 24 | "illuminate/support": "^10.48" 25 | }, 26 | "require-dev": { 27 | "laravel/pint": "^1.0", 28 | "nunomaduro/collision": "^7.8", 29 | "larastan/larastan": "^2.0.1", 30 | "orchestra/testbench": "^8.0", 31 | "pestphp/pest": "^2.0", 32 | "pestphp/pest-plugin-arch": "^2.0", 33 | "pestphp/pest-plugin-laravel": "^2.0", 34 | "phpstan/extension-installer": "^1.1", 35 | "phpstan/phpstan-deprecation-rules": "^1.0", 36 | "phpstan/phpstan-phpunit": "^1.0", 37 | "mockery/mockery": "^1.6", 38 | "spatie/invade": "^2.0" 39 | }, 40 | "config": { 41 | "allow-plugins": { 42 | "pestphp/pest-plugin": true, 43 | "phpstan/extension-installer": true 44 | } 45 | }, 46 | "extra": { 47 | "laravel": { 48 | "providers": [ 49 | "Trovee\\Repository\\Providers\\RepositoryServiceProvider", 50 | "Trovee\\Repository\\Providers\\EventServiceProvider" 51 | ], 52 | "aliases": { 53 | "Repository": "Trovee\\Repository\\Facades\\Repository" 54 | } 55 | } 56 | }, 57 | "scripts": { 58 | "post-autoload-dump": [ 59 | "@prepare", 60 | "@build" 61 | ], 62 | "clear": "@php vendor/bin/testbench package:purge-skeleton --ansi", 63 | "prepare": "@php vendor/bin/testbench package:discover --ansi", 64 | "build": "@php vendor/bin/testbench workbench:build --ansi", 65 | "start": [ 66 | "Composer\\Config::disableProcessTimeout", 67 | "@composer run build", 68 | "@php vendor/bin/testbench serve" 69 | ], 70 | "analyse": "vendor/bin/phpstan analyse", 71 | "test": "vendor/bin/pest", 72 | "test-coverage": "vendor/bin/pest --coverage", 73 | "format": "vendor/bin/pint", 74 | "serve": [ 75 | "Composer\\Config::disableProcessTimeout", 76 | "@build", 77 | "@php vendor/bin/testbench serve" 78 | ], 79 | "lint": [ 80 | "@php vendor/bin/pint", 81 | "@php vendor/bin/phpstan analyse" 82 | ] 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/Managers/RepositoryManager.php: -------------------------------------------------------------------------------- 1 | config = new Config(config('repository')); 25 | } 26 | 27 | public function getDefaultRepositoryAsTargetedToModel(string $model) 28 | { 29 | if (! class_exists($model)) { 30 | throw new ClassNotFoundException($model); 31 | } 32 | 33 | if (! is_subclass_of($model, Model::class)) { 34 | throw new RepositoryIntegrityException( 35 | fqcn: $model, 36 | verb: 'extends', 37 | inheritance: Model::class 38 | ); 39 | } 40 | 41 | $repository = $this->getDefaultRepository(); 42 | 43 | return $repository->proxyOf($model); 44 | } 45 | 46 | public function resolveRepositoryAttribute(string $model): ?RepositoryInterface 47 | { 48 | if (! class_exists($model)) { 49 | return null; 50 | } 51 | 52 | $reflection = new ReflectionClass($model); 53 | 54 | if ($reflection->isAbstract()) { 55 | return null; 56 | } 57 | 58 | /** @var ?ReflectionAttribute $attribute */ 59 | $attribute = collect($reflection->getAttributes(RepositoryAttribute::class))->first(); 60 | 61 | if (is_null($attribute)) { 62 | return null; 63 | } 64 | 65 | $repositoryAttribute = $attribute->newInstance(); 66 | 67 | if (! ($repositoryAttribute instanceof RepositoryAttribute)) { 68 | throw new RepositoryIntegrityException( 69 | fqcn: get_class($repositoryAttribute), 70 | verb: 'be an instance of', 71 | inheritance: RepositoryAttribute::class 72 | ); 73 | } 74 | 75 | return $repositoryAttribute->getRepository($model); 76 | } 77 | 78 | public function getDefaultRepository(): RepositoryInterface 79 | { 80 | $repository = $this->config->get('default_repository'); 81 | 82 | if (is_subclass_of($repository, RepositoryInterface::class)) { 83 | return $this->app->make($this->config->get('default_repository')); 84 | } 85 | 86 | throw new RepositoryIntegrityException( 87 | fqcn: $this->config->get('default_repository'), 88 | verb: 'implements', 89 | inheritance: RepositoryInterface::class 90 | ); 91 | 92 | } 93 | 94 | /** 95 | * @throws ClassException 96 | * @throws ReflectionException 97 | * @throws Throwable 98 | */ 99 | public function get(string $model): RepositoryInterface 100 | { 101 | $repository = $this->resolveRepositoryAttribute($model) 102 | ?? $this->getDefaultRepositoryAsTargetedToModel($model); 103 | 104 | if (! ($repository instanceof RepositoryInterface)) { 105 | throw new RepositoryIntegrityException( 106 | action: 'boot', 107 | fqcn: get_class($repository), 108 | verb: 'implement', 109 | inheritance: RepositoryInterface::class 110 | ); 111 | } 112 | 113 | $repository->boot(); 114 | 115 | return $repository; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/Concerns/Criteria/AppliesCriteria.php: -------------------------------------------------------------------------------- 1 | criteria = collect($this->criteria) 22 | ->map(fn ($criteria) => $this->resolveCriteria($criteria)) 23 | ->toArray(); 24 | } 25 | 26 | /** 27 | * @throws BindingResolutionException 28 | * @throws PhpVersionNotSupportedException 29 | */ 30 | final protected function applyCriteria(): void 31 | { 32 | foreach ($this->criteria as $criteria) { 33 | if ($this->criteriaApplied($criteria)) { 34 | continue; 35 | } 36 | 37 | $this->apply($criteria); 38 | } 39 | } 40 | 41 | final public function criteriaApplied(CriteriaInterface $criteria): bool 42 | { 43 | return isset($this->appliedCriteria[$this->hashCriteria($criteria)]); 44 | } 45 | 46 | final protected function hashCriteria(CriteriaInterface $criteria): string 47 | { 48 | return base64_encode(md5(serialize($criteria))); 49 | } 50 | 51 | /** 52 | * @throws BindingResolutionException 53 | * @throws PhpVersionNotSupportedException 54 | */ 55 | final public function pushCriteria( 56 | string|CriteriaInterface|Closure|SerializableClosure $criteria 57 | ): RepositoryInterface { 58 | $this->criteria[] = $this->resolveCriteria($criteria); 59 | 60 | $this->trigger('criteria:pushed', $criteria); 61 | 62 | return $this; 63 | } 64 | 65 | final public function ignoreCriteria( 66 | string|CriteriaInterface|Closure|SerializableClosure $criteria 67 | ): RepositoryInterface { 68 | $this->criteria = collect($this->criteria) 69 | ->filter(fn ($c) => $this->hashCriteria($c) !== $this->hashCriteria($criteria)) 70 | ->toArray(); 71 | 72 | $this->trigger('criteria:ignored', $criteria); 73 | 74 | return $this; 75 | } 76 | 77 | /** 78 | * @throws BindingResolutionException 79 | * @throws PhpVersionNotSupportedException 80 | */ 81 | final public function resolveCriteria( 82 | string|CriteriaInterface|Closure|SerializableClosure $criteria, 83 | ...$args 84 | ): CriteriaInterface|SerializableClosure { 85 | return match (true) { 86 | is_string($criteria) => app()->make($criteria, $args), 87 | $criteria instanceof Closure, 88 | $criteria instanceof SerializableClosure => new AnonymousCriteria($criteria, $args), 89 | $criteria instanceof CriteriaInterface => $criteria, 90 | }; 91 | } 92 | 93 | /** 94 | * @throws BindingResolutionException 95 | * @throws PhpVersionNotSupportedException 96 | */ 97 | final public function apply( 98 | string|CriteriaInterface|Closure|SerializableClosure $criteria, 99 | ...$args 100 | ): RepositoryInterface { 101 | $criteria = $this->resolveCriteria($criteria, ...$args); 102 | 103 | $this->query = $criteria->apply($this->getBuilder()); 104 | 105 | $this->appliedCriteria[$this->hashCriteria($criteria)] = $criteria; 106 | 107 | $this->trigger('criteria:applied', $criteria); 108 | 109 | return $this; 110 | } 111 | 112 | final protected function clearAppliedCriteria(): void 113 | { 114 | $this->appliedCriteria = []; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/Eloquent/AbstractRepository.php: -------------------------------------------------------------------------------- 1 | createNewBuilder(); 42 | $this->bootTraits(); 43 | 44 | $this->trigger('boot'); 45 | } 46 | 47 | public function proxyOf(string $model): RepositoryInterface 48 | { 49 | $this->model = $model; 50 | 51 | return $this; 52 | } 53 | 54 | public function getBuilder(): Builder 55 | { 56 | if (! isset($this->query)) { 57 | $this->createNewBuilder(); 58 | } 59 | 60 | return $this->query; 61 | } 62 | 63 | public function createNewBuilder(): RepositoryInterface 64 | { 65 | $this->createNewQueryBuilder(); 66 | 67 | if (count($this->appliedCriteria)) { 68 | $this->clearAppliedCriteria(); 69 | } 70 | 71 | return $this; 72 | } 73 | 74 | public function where( 75 | array|string|Expression|Closure $column, 76 | $operator = null, 77 | $value = null, 78 | $boolean = 'and' 79 | ): RepositoryInterface { 80 | 81 | $this->apply( 82 | fn (Builder $builder) => $builder->where($column, $operator, $value, $boolean) 83 | ); 84 | 85 | return $this; 86 | } 87 | 88 | public function __call($method, $parameters) 89 | { 90 | return match (true) { 91 | $this->isCallingExistingMethod($method) => $this->{$method}(...$parameters), 92 | $this->isCallingGetByColumn($method) => $this->firstByAttributes([ 93 | $this->getColumnNameFromMethod($method, 'getBy') => $parameters[0], 94 | ]), 95 | default => $this->forwardCallTo($this->getBuilder(), $method, $parameters), 96 | }; 97 | } 98 | 99 | public function __invoke() 100 | { 101 | if ($this->isHistoryEnabled() && ! $this->isBooted()) { 102 | $this->boot(); 103 | } 104 | } 105 | 106 | protected function isCallingExistingMethod(string $method): bool 107 | { 108 | return method_exists($this, $method); 109 | } 110 | 111 | protected function isCallingSomethingBy(string $method, string $prefix): bool 112 | { 113 | return Str::startsWith($method, $prefix); 114 | } 115 | 116 | protected function getColumnNameFromMethod(string $method, string $prefix): string 117 | { 118 | return Str::snake(Str::after($method, $prefix)); 119 | } 120 | 121 | protected function isCallingGetByColumn(string $method): bool 122 | { 123 | $result = $this->isCallingSomethingBy($method, 'getBy'); 124 | 125 | if ($result) { 126 | $this->trigger('dynamic_call:'.$method); 127 | } 128 | 129 | return $result; 130 | } 131 | 132 | private function detectMultiLevelArray(array $data): bool 133 | { 134 | if (count($data) == count($data, COUNT_RECURSIVE)) { 135 | return false; 136 | } 137 | 138 | $keys = array_keys($data[0]); 139 | 140 | foreach ($data as $item) { 141 | if (! is_array($item)) { 142 | return false; 143 | } 144 | 145 | if (count(array_diff($keys, array_keys($item))) > 0) { 146 | return false; 147 | } 148 | } 149 | 150 | return true; 151 | } 152 | 153 | protected function isBooted(): bool 154 | { 155 | return $this->isHappened('boot'); 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /src/Contracts/RepositoryInterface.php: -------------------------------------------------------------------------------- 1 | getTargetModel(); 19 | 20 | $this->createOrPassModel($model); 21 | 22 | [$interface, $implementation] = $this->createRepositoryElements($model); 23 | 24 | $this->referRepositoryToModel($model, $interface, $implementation); 25 | 26 | $this->components->info("[{$model} Repository] created successfully"); 27 | } 28 | 29 | protected function getTargetModel() 30 | { 31 | $model = $this->option('model'); 32 | 33 | if (! $model) { 34 | $model = $this->ask('What model should the repository be for?'); 35 | } 36 | 37 | return $this->getFullyQualifiedModel($model); 38 | } 39 | 40 | public function convertPathToNamespace(string $path): string 41 | { 42 | return Str::replace('/', '\\', $path); 43 | } 44 | 45 | protected function getModelNamespace(): string 46 | { 47 | return $this->getNamespace('Models'); 48 | } 49 | 50 | protected function getContractNamespace(): string 51 | { 52 | return $this->getNamespace('Repositories\Contracts'); 53 | } 54 | 55 | protected function getImplementationNamespace(): string 56 | { 57 | return $this->getNamespace('Repositories\Eloquent'); 58 | } 59 | 60 | protected function getFullyQualifiedContract(string $contract): string 61 | { 62 | return $this->getContractNamespace().$contract; 63 | } 64 | 65 | protected function getFullyQualifiedImplementation(string $implementation): string 66 | { 67 | return $this->getImplementationNamespace().$implementation; 68 | } 69 | 70 | protected function removeModelNamespace(string $model): string 71 | { 72 | return Str::remove($this->getModelNamespace(), $model); 73 | } 74 | 75 | protected function getRootNamespace(): string 76 | { 77 | return $this->laravel->getNamespace(); 78 | } 79 | 80 | protected function getNamespace(string $namespace): string 81 | { 82 | return $this->getRootNamespace().$namespace.'\\'; 83 | } 84 | 85 | protected function getModelAsStub(string $model): string 86 | { 87 | $relativePath = Str::remove($this->getRootNamespace(), $model); 88 | $path = Str::replace('\\', '/', app_path($relativePath).'.php'); 89 | 90 | return file_get_contents($path); 91 | } 92 | 93 | protected function getConfigAsStub(): string 94 | { 95 | return file_get_contents(config_path('repository.php')); 96 | } 97 | 98 | protected function getFullyQualifiedModel(mixed $model) 99 | { 100 | return $this->convertPathToNamespace( 101 | Str::startsWith($model, $this->getModelNamespace()) 102 | ? $model 103 | : $this->getModelNamespace().$model 104 | ); 105 | } 106 | 107 | protected function createOrPassModel(string $model) 108 | { 109 | if (! class_exists($model)) { 110 | $this->call('make:model', [ 111 | 'name' => $this->removeModelNamespace($model), 112 | '--factory' => true, 113 | '--migration' => true, 114 | ]); 115 | } 116 | } 117 | 118 | protected function createRepositoryElements(string $model) 119 | { 120 | $base = $this->removeModelNamespace($model); 121 | 122 | $this->call(RepositoryInterfaceMakeCommand::class, [ 123 | 'name' => $interface = "{$base}RepositoryContract", 124 | ]); 125 | 126 | $this->call(EloquentRepositoryMakeCommand::class, [ 127 | 'name' => $implementation = "{$base}Repository", 128 | ]); 129 | 130 | return [$this->getFullyQualifiedContract($interface), $this->getFullyQualifiedImplementation($implementation)]; 131 | } 132 | 133 | protected function referRepositoryToModel(string $model, string $interface, string $implementation) 134 | { 135 | $this->components->info('Adding repository attribute to model...'); 136 | $this->addClassAttribute( 137 | model: $model, 138 | abstract: $interface, 139 | ); 140 | 141 | $this->components->info('Adding binding configuration...'); 142 | $this->addBindingConfig( 143 | abstract: $interface, 144 | concrete: $implementation, 145 | ); 146 | } 147 | 148 | protected function addClassAttribute(string $model, string $abstract): void 149 | { 150 | $content = $this->getModelAsStub($model); 151 | 152 | $className = class_basename($model); 153 | $useConverter = fn ($use) => "use $use;"; 154 | 155 | $shortAbstract = class_basename($abstract); 156 | 157 | $uses = $this->getImports($content) 158 | ->merge([Repository::class, $abstract]) 159 | ->unique() 160 | ->map($useConverter) 161 | ->sort(fn ($a, $b) => Str::length($a) <=> Str::length($b)); 162 | 163 | $replacements = [ 164 | '#[Repository({$shortAbstract}::class)]'.PHP_EOL => '', 165 | $this->getImports($content)->map($useConverter)->implode(PHP_EOL) => $uses->implode(PHP_EOL), 166 | "class {$className} " => "#[Repository({$shortAbstract}::class)]".PHP_EOL."class {$className} ", 167 | ]; 168 | 169 | $content = Str::replace(array_keys($replacements), array_values($replacements), $content); 170 | 171 | file_put_contents(app_path($this->removeModelNamespace('Models\\'.$model).'.php'), $content); 172 | } 173 | 174 | protected function getImports(string $content): Collection 175 | { 176 | preg_match_all('/use (.*);/', $content, $matches); 177 | 178 | return collect($matches[1])->filter(fn ($use) => $this->isFqcn($use)); 179 | } 180 | 181 | protected function isFqcn(string $class): bool 182 | { 183 | return Str::contains($class, '\\'); 184 | } 185 | 186 | protected function addBindingConfig(string $abstract, string $concrete) 187 | { 188 | $config = $this->getBindings($content = $this->getConfigAsStub()) 189 | ->put($abstract, $concrete) 190 | ->unique() 191 | ->map(fn ($concrete, $abstract) => "\t\t{$abstract}::class => {$concrete}::class,") 192 | ->values() 193 | ->toArray(); 194 | 195 | usort($config, fn ($a, $b) => Str::startsWith($a, '//') > Str::startsWith($b, '//')); 196 | 197 | $config = implode(PHP_EOL, $config); 198 | 199 | $keyword = "'bindings' => ["; 200 | 201 | $content = preg_replace( 202 | '/'.preg_quote($keyword).'(.*)\]\,/s', 203 | $keyword.PHP_EOL.$config.PHP_EOL."\t],", 204 | $content, 205 | 1 206 | ); 207 | 208 | file_put_contents(config_path('repository.php'), $content); 209 | } 210 | 211 | protected function getBindings(string $content): Collection 212 | { 213 | preg_match_all('/\'bindings\' => \[(.*)\]/s', $content, $matches); 214 | 215 | $clear = fn ($binding) => Str::remove(['::class', ','], trim($binding)); 216 | 217 | return collect(explode(PHP_EOL, $matches[1][0])) 218 | ->map(fn ($binding) => explode(' => ', $binding)) 219 | ->reject(fn ($binding) => count($binding) < 2) 220 | ->mapWithKeys(fn ($binding) => [$clear($binding[0]) => $clear($binding[1])]); 221 | } 222 | } 223 | --------------------------------------------------------------------------------