AfterRule.php
3 weeks ago
ArrayRule.php
3 weeks ago
BaseRule.php
3 weeks ago
BooleanRule.php
3 weeks ago
DateFormatRule.php
3 weeks ago
DateRule.php
3 weeks ago
DateTimeRule.php
3 weeks ago
EmailRule.php
3 weeks ago
EmailUniqueRule.php
3 weeks ago
ExistsRule.php
3 weeks ago
FloatRule.php
3 weeks ago
GreaterThanEqualRule.php
3 weeks ago
GreaterThanRule.php
3 weeks ago
InRule.php
3 weeks ago
IntegerRule.php
3 weeks ago
IsValidImageIdRule.php
3 weeks ago
LessThanEqualRule.php
3 weeks ago
LessThanRule.php
3 weeks ago
MaxRule.php
3 weeks ago
MinRule.php
3 weeks ago
NotInRule.php
3 weeks ago
NullableRule.php
3 weeks ago
NumberRule.php
3 weeks ago
ObjectRule.php
3 weeks ago
ProhibitedIfRule.php
3 weeks ago
ProhibitedRule.php
3 weeks ago
RegexRule.php
3 weeks ago
RequiredIfExists.php
3 weeks ago
RequiredIfRule.php
3 weeks ago
RequiredIfSiblingRule.php
3 weeks ago
RequiredRule.php
3 weeks ago
SameAsRule.php
3 weeks ago
Sanitizer.php
3 weeks ago
StringRule.php
3 weeks ago
UniqueRule.php
3 weeks ago
UrlRule.php
3 weeks ago
UserExists.php
3 weeks ago
UniqueRule.php
55 lines
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * Rule to ensure that a value is unique in a specified database table and column. |
| 5 | * |
| 6 | * @package Framework |
| 7 | * @subpackage Validation\Rules |
| 8 | * @since 1.0.0 |
| 9 | */ |
| 10 | namespace Kirki\Framework\Validation\Rules; |
| 11 | |
| 12 | \defined('ABSPATH') || exit; |
| 13 | use Kirki\Framework\Supports\Facades\DB; |
| 14 | use Exception; |
| 15 | use function Kirki\Framework\message; |
| 16 | class UniqueRule extends BaseRule |
| 17 | { |
| 18 | /** |
| 19 | * Check if the value unique in the specified database table and column. |
| 20 | * |
| 21 | * @return bool |
| 22 | * |
| 23 | * @throws \Exception |
| 24 | * |
| 25 | * @since 1.0.0 |
| 26 | */ |
| 27 | public function validate_rule() |
| 28 | { |
| 29 | if (\stripos($this->rule_value, ',') === \false) { |
| 30 | throw new Exception("Missing parameters for unique rule."); |
| 31 | } |
| 32 | $parts = \explode(',', $this->rule_value, 3); |
| 33 | $table_name = $parts[0]; |
| 34 | $column_name = $parts[1] ?? ''; |
| 35 | $id = $parts[2] ?? null; |
| 36 | if (!empty($id)) { |
| 37 | $result = DB::table($table_name)->where($column_name, $this->value)->where('id', '!=', $id)->first(); |
| 38 | } else { |
| 39 | $result = DB::table($table_name)->where($column_name, $this->value)->first(); |
| 40 | } |
| 41 | return empty($result); |
| 42 | } |
| 43 | /** |
| 44 | * Get the error message if the row exist in DB table. |
| 45 | * |
| 46 | * @return string |
| 47 | * |
| 48 | * @since 1.0.0 |
| 49 | */ |
| 50 | public function get_error_message() |
| 51 | { |
| 52 | return message('validator.unique', $this->last_key_segment()); |
| 53 | } |
| 54 | } |
| 55 |