Skip to content

Commit

Permalink
Merge pull request #1 from korridor/feature/unique_eloquent
Browse files Browse the repository at this point in the history
Added UniqueEloquent rule; Renamed ExistEloquent to ExistsEloquent
  • Loading branch information
korridor authored Sep 18, 2019
2 parents 87a0f9e + 5a29192 commit da57c42
Show file tree
Hide file tree
Showing 19 changed files with 602 additions and 66 deletions.
15 changes: 15 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
; This file is for unifying the coding style for different editors and IDEs.
; More information at http://editorconfig.org

root = true

[*]
charset = utf-8
indent_size = 4
indent_style = space
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false
12 changes: 1 addition & 11 deletions .php_cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,7 @@
return PhpCsFixer\Config::create()
->setRiskyAllowed(false)
->setRules([
'@Symfony' => true,
'array_syntax' => ['syntax' => 'short'],
'ordered_imports' => true,
'protected_to_private' => false,
// Part of future @Symfony ruleset in PHP-CS-Fixer To be removed from the config file once upgrading
'phpdoc_types_order' => ['null_adjustment' => 'always_last', 'sort_algorithm' => 'none'],
// custom
'phpdoc_separation' => false,
'phpdoc_align' => false,
'phpdoc_no_alias_tag' => false,
'array_indentation' => true,
'@PSR2' => true,
])
->setUsingCache(true)
->setFinder(
Expand Down
1 change: 1 addition & 0 deletions .styleci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
preset: laravel
54 changes: 54 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
cache:
directories:
- $HOME/.composer/cache

language: php

matrix:
include:
- php: 7.1
env: LARAVEL='5.6.*' TESTBENCH='3.6.*' COMPOSER_FLAGS='--prefer-stable'
- php: 7.2
env: LARAVEL='5.6.*' TESTBENCH='3.6.*' COMPOSER_FLAGS='--prefer-stable'
- php: 7.3
env: LARAVEL='5.6.*' TESTBENCH='3.6.*' COMPOSER_FLAGS='--prefer-stable'
- php: 7.1
env: LARAVEL='5.7.*' TESTBENCH='3.7.*' COMPOSER_FLAGS='--prefer-stable'
- php: 7.2
env: LARAVEL='5.7.*' TESTBENCH='3.7.*' COMPOSER_FLAGS='--prefer-stable'
- php: 7.3
env: LARAVEL='5.7.*' TESTBENCH='3.7.*' COMPOSER_FLAGS='--prefer-stable'
- php: 7.1
env: LARAVEL='5.8.*' TESTBENCH='3.8.*' COMPOSER_FLAGS='--prefer-lowest'
- php: 7.1
env: LARAVEL='5.8.*' TESTBENCH='3.8.*' COMPOSER_FLAGS='--prefer-stable'
- php: 7.2
env: LARAVEL='5.8.*' TESTBENCH='3.8.*' COMPOSER_FLAGS='--prefer-lowest'
- php: 7.2
env: LARAVEL='5.8.*' TESTBENCH='3.8.*' COMPOSER_FLAGS='--prefer-stable'
- php: 7.3
env: LARAVEL='5.8.*' TESTBENCH='3.8.*' COMPOSER_FLAGS='--prefer-lowest'
- php: 7.3
env: LARAVEL='5.8.*' TESTBENCH='3.8.*' COMPOSER_FLAGS='--prefer-stable'
- php: 7.2
env: LARAVEL='6.*' TESTBENCH='4.*' COMPOSER_FLAGS='--prefer-lowest'
- php: 7.2
env: LARAVEL='6.*' TESTBENCH='4.*' COMPOSER_FLAGS='--prefer-stable'
- php: 7.3
env: LARAVEL='6.*' TESTBENCH='4.*' COMPOSER_FLAGS='--prefer-lowest'
- php: 7.3
env: LARAVEL='6.*' TESTBENCH='4.*' COMPOSER_FLAGS='--prefer-stable'
fast_finish: true

before_install:
- travis_retry composer self-update
- travis_retry composer require "laravel/framework:${LARAVEL}" "orchestra/testbench:${TESTBENCH}" --no-interaction --no-update

install:
- travis_retry composer update ${COMPOSER_FLAGS} --prefer-dist --no-interaction --no-suggest

before_script:
- composer config discard-changes true

script:
- vendor/bin/phpunit --coverage-text
11 changes: 4 additions & 7 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
],
"license": "MIT",
"require": {
"php": "7.*",
"illuminate/support": "^5.8|^6.0"
"php": "^7.1|^7.2|^7.3",
"illuminate/support": "^5.6|^5.7|^5.8|^6.0"
},
"require-dev": {
"orchestra/testbench": "^3.5|^4.0",
"orchestra/testbench": "^3.6|^3.7|^3.8|^4.0",
"phpunit/phpunit": "^7.0|^8.0",
"friendsofphp/php-cs-fixer": "^2.15",
"squizlabs/php_codesniffer": "^3.4"
Expand Down Expand Up @@ -44,9 +44,6 @@
}
},
"config": {
"sort-packages": true,
"platform": {
"php": "7.1"
}
"sort-packages": true
}
}
14 changes: 7 additions & 7 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions phpcs.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@
</rule>

<file>src/</file>
<file>resources/</file>
<file>tests/</file>
</ruleset>
2 changes: 1 addition & 1 deletion phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
stopOnFailure="false">
<testsuites>
<testsuite name="Feature">
<directory>tests</directory>
<directory>tests/Feature</directory>
</testsuite>
</testsuites>
<filter>
Expand Down
65 changes: 63 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,69 @@
# Laravel model validation rules

[![Latest Version on Packagist](https://img.shields.io/packagist/v/korridor/laravel-model-validation-rules?style=flat-square)](https://packagist.org/packages/korridor/laravel-model-validation-rules)
[![License](https://img.shields.io/packagist/l/korridor/laravel-model-validation-rules?style=flat-square)](license.md)
[![TravisCI](https://img.shields.io/travis/korridor/laravel-model-validation-rules?style=flat-square)](https://travis-ci.org/korridor/laravel-model-validation-rules)
[![StyleCI](https://styleci.io/repos/208495858/shield)](https://styleci.io/repos/208495858)

This package is an alternative to the Laravel built-in validation rules `exists` and `unique`.
It uses Eloquent models instead of directly querying the database.

**Advantages**
- The rule can be easily extended with the Eloquent builder. (scopes etc.)
- Softdeletes are working out of the box.
- Logic implemented into the models work in the validation as well. (multi tenancy system, etc.)

## Installation

You can install the package via composer with following command:

```bash
composer require korridor/laravel-model-validation-rules
```

### Translation

If you want to customize the translations of the validation errors you can publish the translations
of the package to the `resources/lang/vendor/modelValidationRules` folder.

```bash
php artisan vendor:publish --provider="Korridor\LaravelModelValidationRules\ModelValidationServiceProvider"
```

## Usage
### Requirements

This package is tested for the following Laravel versions:

- 6.0
- 5.8
- 5.7 (stable only)
- 5.6 (stable only)

## Usage examples

**PostStoreRequest**

```php
public function rules()
{
$postId = $this->post->id;

return [
'username' => [new UniqueEloquent(User::class, 'username')],
'title' => ['string'],
'content' => ['string'],
'comments.*.id' => [
'nullable',
new ExistEloquent(Comment::class, null, function (Builder $builder) use ($postId) {
return $builder->where('post_id', $postId);
}),
],
'comments.*.content' => ['string']
];
}
```

**PostUpdateRequest**

```php
public function rules()
Expand All @@ -19,6 +72,7 @@ public function rules()

return [
'id' => [new ExistEloquent(Post::class)],
'username' => [new UniqueEloquent(User::class, 'username')->ignore($postId)],
'title' => ['string'],
'content' => ['string'],
'comments.*.id' => [
Expand All @@ -34,6 +88,8 @@ public function rules()

## Contributing

I am open for suggestions and contributions. Just create an issue or a pull request.

### Testing

```bash
Expand All @@ -48,6 +104,11 @@ composer fix
composer lint
```

## Credits

The structure of the repository and the TestClass is inspired by the
project [laravel-validation-rules](https://github.com/spatie/laravel-validation-rules) by [spatie](https://github.com/spatie).

## License

The MIT License (MIT). Please see [license file](license.md) for more information.
This package is licensed under the MIT License (MIT). Please see [license file](license.md) for more information.
3 changes: 2 additions & 1 deletion resources/lang/de/validation.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php

return [
'exist_model' => 'Die Ressource existiert nicht.'
'exists_model' => 'Die Ressource existiert nicht.',
'unique_model' => 'Die Ressource existiert bereits.',
];
3 changes: 2 additions & 1 deletion resources/lang/en/validation.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php

return [
'exist_model' => 'The resource does not exist.'
'exists_model' => 'The resource does not exist.',
'unique_model' => 'The resource already exists.',
];
8 changes: 4 additions & 4 deletions src/ModelValidationServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ public function register()
*/
public function boot()
{
$this->publishes([
__DIR__.'/../resources/lang' => resource_path('lang/vendor/modelValidationRules'),
]);
$this->loadTranslationsFrom(__DIR__.'/../resources/lang/', 'modelValidationRules');
$this->publishes([
__DIR__.'/../resources/lang' => resource_path('lang/vendor/modelValidationRules'),
]);
$this->loadTranslationsFrom(__DIR__.'/../resources/lang/', 'modelValidationRules');
}
}
39 changes: 29 additions & 10 deletions src/Rules/ExistEloquent.php → src/Rules/ExistsEloquent.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
namespace Korridor\LaravelModelValidationRules\Rules;

use Closure;
use Eloquent;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Validation\Rule;

class ExistEloquent implements Rule
class ExistsEloquent implements Rule
{
/**
* @var string
Expand Down Expand Up @@ -44,7 +44,7 @@ public function __construct(string $model, ?string $key = null, ?Closure $builde
{
$this->model = $model;
$this->key = $key;
$this->builderClosure = $builderClosure;
$this->setBuilderClosure($builderClosure);
}

/**
Expand All @@ -58,10 +58,10 @@ public function passes($attribute, $value): bool
{
$this->attribute = $attribute;
$this->value = $value;
/** @var Eloquent $builder */
/** @var Model $builder */
$builder = new $this->model();
if (null === $this->key) {
$builder = $builder->where($builder->getKeyName(), $value);
$builder = $builder->where((new $this->model())->getKeyName(), $value);
} else {
$builder = $builder->where($this->key, $value);
}
Expand All @@ -80,10 +80,29 @@ public function passes($attribute, $value): bool
*/
public function message(): string
{
return trans('modelValidationRules::validation.exist_model', [
'attribute' => $this->attribute,
'model' => class_basename($this->model),
'value' => $this->value,
]);
return trans('modelValidationRules::validation.exists_model', [
'attribute' => $this->attribute,
'model' => class_basename($this->model),
'value' => $this->value,
]);
}

/**
* @param Closure|null $builderClosure
*/
public function setBuilderClosure(?Closure $builderClosure)
{
$this->builderClosure = $builderClosure;
}

/**
* @param Closure $builderClosure
* @return $this
*/
public function query(Closure $builderClosure): self
{
$this->setBuilderClosure($builderClosure);

return $this;
}
}
Loading

0 comments on commit da57c42

Please sign in to comment.