ArrayRule.php
6 days ago
BooleanRule.php
6 days ago
ConditionalRule.php
6 days ago
DateRule.php
6 days ago
ExistsRule.php
6 days ago
FileRule.php
6 days ago
InRule.php
6 days ago
NotInRule.php
6 days ago
NullableRule.php
6 days ago
NumericRule.php
6 days ago
ObjectRule.php
6 days ago
ProhibitedIfRule.php
6 days ago
ProhibitedRule.php
6 days ago
ProhibitedUnlessRule.php
6 days ago
RequiredIfRule.php
6 days ago
RequiredRule.php
6 days ago
RequiredUnlessRule.php
6 days ago
SameAsRule.php
6 days ago
SometimesRule.php
6 days ago
StringRule.php
6 days ago
UniqueRule.php
6 days ago
ExistsRule.php
87 lines
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * Exists rule class. |
| 5 | * |
| 6 | * @package Framework |
| 7 | * @subpackage Validation |
| 8 | * @since 1.0.0 |
| 9 | */ |
| 10 | namespace Kirki\Framework\Validation\Rules; |
| 11 | |
| 12 | use Kirki\Framework\Supports\Arr; |
| 13 | use Kirki\Framework\Supports\Facades\DB; |
| 14 | use Kirki\Framework\Validation\ValidationRule; |
| 15 | use function Kirki\Framework\Polyfill\array_last; |
| 16 | \defined('ABSPATH') || exit; |
| 17 | /** |
| 18 | * Validates that the given value exists in a database table column. |
| 19 | */ |
| 20 | class ExistsRule extends ValidationRule |
| 21 | { |
| 22 | /** |
| 23 | * The rule name. |
| 24 | * |
| 25 | * @var string |
| 26 | * |
| 27 | * @since 1.0.0 |
| 28 | */ |
| 29 | protected string $rule = 'exists'; |
| 30 | /** |
| 31 | * Validate the rule. |
| 32 | * |
| 33 | * @return bool |
| 34 | * |
| 35 | * @since 1.0.0 |
| 36 | */ |
| 37 | public function validate() : bool |
| 38 | { |
| 39 | if (!$this->record_exists()) { |
| 40 | return $this->fails($this->default_messages['default']); |
| 41 | } |
| 42 | return \true; |
| 43 | } |
| 44 | /** |
| 45 | * Check whether a matching record exists in the table. |
| 46 | * |
| 47 | * @return bool |
| 48 | * |
| 49 | * @since 1.0.0 |
| 50 | */ |
| 51 | protected function record_exists() |
| 52 | { |
| 53 | [$table, $column] = $this->table_and_column(); |
| 54 | $values = Arr::wrap($this->value); |
| 55 | if (empty($values)) { |
| 56 | return \false; |
| 57 | } |
| 58 | $total = DB::table($table)->where_in($column, $values)->count(); |
| 59 | return $total === \count($values); |
| 60 | } |
| 61 | /** |
| 62 | * Resolve the prefixed table name and the column from the rule arguments. |
| 63 | * |
| 64 | * @return array |
| 65 | * |
| 66 | * @since 1.0.0 |
| 67 | */ |
| 68 | protected function table_and_column() |
| 69 | { |
| 70 | $arguments = Arr::wrap($this->args); |
| 71 | $table = $arguments[0]; |
| 72 | $column = $arguments[1] ?? array_last(\explode('.', $this->name)); |
| 73 | return [$table, $column]; |
| 74 | } |
| 75 | /** |
| 76 | * Get the error messages. |
| 77 | * |
| 78 | * @return array |
| 79 | * |
| 80 | * @since 1.0.0 |
| 81 | */ |
| 82 | public function messages() |
| 83 | { |
| 84 | return $this->process_messages($this->messages); |
| 85 | } |
| 86 | } |
| 87 |