Skip to content

Commit d65cf4c

Browse files
committed
Add custom rules selection & user password validation rule
1 parent b245335 commit d65cf4c

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

src/Validators/Rules/Rules.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
3+
namespace Sprocketbox\Toolkit\Validators\Rules;
4+
5+
use Illuminate\Database\Eloquent\Model;
6+
use Illuminate\Validation\Rules\Unique;
7+
8+
class Rules
9+
{
10+
/**
11+
* @param \Illuminate\Database\Eloquent\Model|string $model
12+
* @param string|null $column
13+
*
14+
* @return \Illuminate\Validation\Rules\Unique
15+
*/
16+
public static function unique($model, ?string $column = null): Unique
17+
{
18+
$instance = $model instanceof Model ? $model : new $model;
19+
$rule = new Unique($instance->getTable(), $column ?? 'NULL');
20+
21+
if ($model instanceof Model) {
22+
$rule->ignoreModel($model);
23+
}
24+
25+
return $rule;
26+
}
27+
28+
public static function password(?string $guard = null): UserPassword
29+
{
30+
return new UserPassword($guard);
31+
}
32+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
3+
namespace Sprocketbox\Toolkit\Validators\Rules;
4+
5+
use Illuminate\Contracts\Validation\Rule;
6+
use Illuminate\Support\Facades\Auth;
7+
use Illuminate\Support\Facades\Hash;
8+
9+
class UserPassword implements Rule
10+
{
11+
/**
12+
* @var string|null
13+
*/
14+
protected ?string $guard;
15+
16+
public function __construct(?string $guard = null)
17+
{
18+
$this->guard = $guard;
19+
}
20+
21+
/**
22+
* @inheritDoc
23+
*/
24+
public function passes($attribute, $value)
25+
{
26+
$user = Auth::guard($this->guard)->user();
27+
28+
if ($user !== null) {
29+
return Hash::check($value, $user->getAuthPassword());
30+
}
31+
32+
return false;
33+
}
34+
35+
/**
36+
* @inheritDoc
37+
*/
38+
public function message()
39+
{
40+
return 'validation.user_password';
41+
}
42+
}

0 commit comments

Comments
 (0)