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

[11.x] Added ModelExists rule #52505

Draft
wants to merge 3 commits into
base: 11.x
Choose a base branch
from
Draft
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
14 changes: 14 additions & 0 deletions src/Illuminate/Validation/Rule.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

namespace Illuminate\Validation;

use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Validation\Rules\ArrayRule;
use Illuminate\Validation\Rules\Can;
Expand All @@ -13,6 +15,7 @@
use Illuminate\Validation\Rules\File;
use Illuminate\Validation\Rules\ImageFile;
use Illuminate\Validation\Rules\In;
use Illuminate\Validation\Rules\ModelExists;
use Illuminate\Validation\Rules\NotIn;
use Illuminate\Validation\Rules\ProhibitedIf;
use Illuminate\Validation\Rules\RequiredIf;
Expand Down Expand Up @@ -106,6 +109,17 @@ public static function exists($table, $column = 'NULL')
return new Exists($table, $column);
}

/**
* Get an ModelExists constraint builder instance.
*
* @param Builder<TModel>|TModel|class-string<TModel> $model
* @return \Illuminate\Validation\Rules\ModelExists<Builder<TModel>>
*/
public static function modelExists(Builder|Model|string $model, ?string $column = null): ModelExists
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about relations?

Copy link
Contributor Author

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.

{
return ModelExists::make($model, $column);
}

/**
* Get an in rule builder instance.
*
Expand Down
88 changes: 88 additions & 0 deletions src/Illuminate/Validation/Rules/ModelExists.php
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]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can remove ['attribute' => $attribute] and leave only ->translate()

}
}

/**
* 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;
}
}
176 changes: 176 additions & 0 deletions tests/Validation/ValidationModelExistsRuleTest.php
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');
}
}