-
Notifications
You must be signed in to change notification settings - Fork 11k
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
[11.x] Added ModelExists
rule
#52505
Draft
pascalbaljet
wants to merge
3
commits into
laravel:11.x
Choose a base branch
from
pascalbaljet:rule-model-exists
base: 11.x
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+278
−0
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
<?php | ||
|
||
namespace Illuminate\Validation\Rules; | ||
|
||
use Closure; | ||
use Illuminate\Contracts\Database\Eloquent\Builder; | ||
use Illuminate\Contracts\Validation\ValidationRule; | ||
use Illuminate\Database\Eloquent\Model; | ||
use Illuminate\Support\Traits\ForwardsCalls; | ||
|
||
/** | ||
* @template TModel of Model | ||
* | ||
* @mixin Builder<TModel> | ||
*/ | ||
class ModelExists implements ValidationRule | ||
{ | ||
use ForwardsCalls; | ||
|
||
/** | ||
* Create a new rule instance. | ||
*/ | ||
public function __construct( | ||
protected Builder $query, | ||
protected ?string $column | ||
) { | ||
// | ||
} | ||
|
||
/** | ||
* Create a new rule instance with the given Builder, Model, or class name. | ||
* | ||
* @template TModel of Model | ||
* | ||
* @param Builder<TModel>|TModel|class-string<TModel> $model | ||
* @return ModelExists<TModel> | ||
*/ | ||
public static function make(Builder|Model|string $model, ?string $column = null): self | ||
{ | ||
$builder = match (true) { | ||
$model instanceof Builder => $model, | ||
$model instanceof Model => $model->query(), | ||
default => $model::query(), | ||
}; | ||
|
||
return new self($builder, $column); | ||
} | ||
|
||
/** | ||
* Run the validation rule. | ||
* | ||
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail | ||
*/ | ||
public function validate(string $attribute, mixed $value, Closure $fail): void | ||
{ | ||
$this->column | ||
? $this->query->where($this->column, $value) | ||
: $this->query->whereKey($value); | ||
|
||
if (! $this->query->exists()) { | ||
$fail('validation.exists')->translate(['attribute' => $attribute]); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think you can remove |
||
} | ||
} | ||
|
||
/** | ||
* Get the underlying query builder instance. | ||
* | ||
* @return Builder<TModel> | ||
*/ | ||
public function getQueryBuilder(): Builder | ||
{ | ||
return $this->query; | ||
} | ||
|
||
/** | ||
* Dynamically handle calls into the query instance. | ||
* | ||
* @param string $method | ||
* @param array $parameters | ||
* @return mixed | ||
*/ | ||
public function __call($method, $parameters) | ||
{ | ||
$this->forwardCallTo($this->query, $method, $parameters); | ||
|
||
return $this; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,176 @@ | ||
<?php | ||
|
||
namespace Illuminate\Tests\Validation; | ||
|
||
use Illuminate\Database\Capsule\Manager as DB; | ||
use Illuminate\Database\Eloquent\Builder; | ||
use Illuminate\Database\Eloquent\Model as Eloquent; | ||
use Illuminate\Translation\ArrayLoader; | ||
use Illuminate\Translation\Translator; | ||
use Illuminate\Validation\Rule; | ||
use Illuminate\Validation\Validator; | ||
use PHPUnit\Framework\TestCase; | ||
|
||
class ValidationModelExistsRuleTest extends TestCase | ||
{ | ||
/** | ||
* Setup the database schema. | ||
*/ | ||
protected function setUp(): void | ||
{ | ||
$db = new DB; | ||
|
||
$db->addConnection([ | ||
'driver' => 'sqlite', | ||
'database' => ':memory:', | ||
]); | ||
|
||
$db->bootEloquent(); | ||
$db->setAsGlobal(); | ||
|
||
$this->createSchema(); | ||
} | ||
|
||
public function testItCanPassAnEloquentBuilderInstance() | ||
{ | ||
$rule = Rule::modelExists(UserModel::query()); | ||
$this->assertInstanceOf(Builder::class, $rule->getQueryBuilder()); | ||
$this->assertInstanceOf(UserModel::class, $rule->getQueryBuilder()->getModel()); | ||
} | ||
|
||
public function testItCanPassAModelInstance() | ||
{ | ||
$rule = Rule::modelExists(new UserModel); | ||
$this->assertInstanceOf(Builder::class, $rule->getQueryBuilder()); | ||
$this->assertInstanceOf(UserModel::class, $rule->getQueryBuilder()->getModel()); | ||
} | ||
|
||
public function testItCanPassAModelClassName() | ||
{ | ||
$rule = Rule::modelExists(UserModel::class); | ||
$this->assertInstanceOf(Builder::class, $rule->getQueryBuilder()); | ||
$this->assertInstanceOf(UserModel::class, $rule->getQueryBuilder()->getModel()); | ||
} | ||
|
||
public function testItForwardsCallsToTheQueryBuilder() | ||
{ | ||
$rule = Rule::modelExists(UserModel::class); | ||
$rule->where('foo', 'bar'); | ||
$this->assertSame('select * from "users" where "foo" = ?', $rule->getQueryBuilder()->toSql()); | ||
} | ||
|
||
public function testPassesWhenRecordExists() | ||
{ | ||
$rule = Rule::modelExists(UserModel::class); | ||
|
||
UserModel::create(['id' => 1, 'type' => 'foo']); | ||
|
||
$trans = $this->getIlluminateArrayTranslator(); | ||
$trans->addLines(['validation.exists' => 'The selected :attribute is invalid.'], 'en'); | ||
$v = new Validator($trans, ['id' => 1], ['id' => $rule]); | ||
$this->assertTrue($v->passes()); | ||
|
||
$v = new Validator($trans, ['id' => 2], ['id' => $rule]); | ||
$this->assertFalse($v->passes()); | ||
$this->assertSame('The selected id is invalid.', $v->errors()->first('id')); | ||
} | ||
|
||
public function testPassesWhenRecordExistsWithScope() | ||
{ | ||
$rule = Rule::modelExists(UserModel::class)->typeFoo(); | ||
|
||
UserModel::create(['id' => 1, 'type' => 'foo']); | ||
UserModel::create(['id' => 2, 'type' => 'bar']); | ||
|
||
$trans = $this->getIlluminateArrayTranslator(); | ||
$v = new Validator($trans, ['id' => 1], ['id' => $rule]); | ||
$this->assertTrue($v->passes()); | ||
|
||
$v = new Validator($trans, ['id' => 2], ['id' => $rule]); | ||
$this->assertFalse($v->passes()); | ||
} | ||
|
||
public function testPassesWhenRecordExistsWithColumn() | ||
{ | ||
$rule = Rule::modelExists(UserModel::class, 'type'); | ||
|
||
UserModel::create(['id' => 1, 'type' => 'foo']); | ||
|
||
$trans = $this->getIlluminateArrayTranslator(); | ||
$v = new Validator($trans, ['id' => 'foo'], ['id' => $rule]); | ||
$this->assertTrue($v->passes()); | ||
|
||
$v = new Validator($trans, ['id' => 'bar'], ['id' => $rule]); | ||
$this->assertFalse($v->passes()); | ||
} | ||
|
||
protected function createSchema() | ||
{ | ||
$this->schema('default')->create('users', function ($table) { | ||
$table->unsignedInteger('id'); | ||
$table->string('type'); | ||
}); | ||
} | ||
|
||
/** | ||
* Get a schema builder instance. | ||
* | ||
* @return \Illuminate\Database\Schema\Builder | ||
*/ | ||
protected function schema($connection = 'default') | ||
{ | ||
return $this->connection($connection)->getSchemaBuilder(); | ||
} | ||
|
||
/** | ||
* Get a database connection instance. | ||
* | ||
* @return \Illuminate\Database\Connection | ||
*/ | ||
protected function connection($connection = 'default') | ||
{ | ||
return $this->getConnectionResolver()->connection($connection); | ||
} | ||
|
||
/** | ||
* Get connection resolver. | ||
* | ||
* @return \Illuminate\Database\ConnectionResolverInterface | ||
*/ | ||
protected function getConnectionResolver() | ||
{ | ||
return Eloquent::getConnectionResolver(); | ||
} | ||
|
||
/** | ||
* Tear down the database schema. | ||
*/ | ||
protected function tearDown(): void | ||
{ | ||
$this->schema('default')->drop('users'); | ||
} | ||
|
||
public function getIlluminateArrayTranslator() | ||
{ | ||
return new Translator( | ||
new ArrayLoader, 'en' | ||
); | ||
} | ||
} | ||
|
||
/** | ||
* Eloquent Models. | ||
*/ | ||
class UserModel extends Eloquent | ||
{ | ||
protected $table = 'users'; | ||
|
||
protected $guarded = []; | ||
|
||
public $timestamps = false; | ||
|
||
public function scopeTypeFoo($query) | ||
{ | ||
$query->where('type', 'foo'); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What about relations?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It uses the Builder contract (
Illuminate\Contracts\Database\Eloquent\Builder
) which is implemented by all relation classes.