|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Chr15k\MysqlEncrypt\Traits; |
| 4 | + |
| 5 | +use PDOException; |
| 6 | +use InvalidArgumentException; |
| 7 | +use Illuminate\Support\Facades\DB; |
| 8 | +use Illuminate\Support\Facades\Schema; |
| 9 | +use Illuminate\Support\Facades\Validator; |
| 10 | + |
| 11 | +trait ValidatesEncrypted |
| 12 | +{ |
| 13 | + /** |
| 14 | + * Validators. |
| 15 | + * |
| 16 | + * @return void |
| 17 | + */ |
| 18 | + public function addValidators() |
| 19 | + { |
| 20 | + Validator::extend('unique_encrypted', function ($attribute, $value, array $parameters) { |
| 21 | + |
| 22 | + $this->requireParameterCount(1, $parameters, 'unique_encrypted'); |
| 23 | + |
| 24 | + $this->requireTableExists($parameters[0]); |
| 25 | + |
| 26 | + $field = isset($parameters[1]) ? $parameters[1] : $attribute; |
| 27 | + $ignore = isset($parameters[2]) ? $parameters[2] : null; |
| 28 | + |
| 29 | + $items = DB::select("SELECT count(*) as aggregate FROM `".$parameters[0]."` WHERE AES_DECRYPT(`".$field."`, '".config("app.key")."') LIKE '".$value."' COLLATE utf8mb4_general_ci".($ignore ? " AND id != ".$ignore : '')); |
| 30 | + |
| 31 | + return $items[0]->aggregate === 0; |
| 32 | + }); |
| 33 | + |
| 34 | + Validator::extend('exists_encrypted', function ($attribute, $value, array $parameters) { |
| 35 | + |
| 36 | + $this->requireParameterCount(1, $parameters, 'exists_encrypted'); |
| 37 | + |
| 38 | + $this->requireTableExists($parameters[0]); |
| 39 | + |
| 40 | + $field = isset($parameters[1]) ? $parameters[1] : $attribute; |
| 41 | + |
| 42 | + $items = DB::select("SELECT count(*) as aggregate FROM `".$parameters[0]."` WHERE AES_DECRYPT(`".$field."`, '".config("app.key")."') LIKE '".$value."' COLLATE utf8mb4_general_ci"); |
| 43 | + |
| 44 | + return $items[0]->aggregate > 0; |
| 45 | + }); |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Require a certain number of parameters to be present. |
| 50 | + * |
| 51 | + * @param int $count |
| 52 | + * @param array $parameters |
| 53 | + * @param string $rule |
| 54 | + * @return void |
| 55 | + * |
| 56 | + * @throws \InvalidArgumentException |
| 57 | + */ |
| 58 | + public function requireParameterCount($count, $parameters, $rule) |
| 59 | + { |
| 60 | + if (count($parameters) < $count) { |
| 61 | + throw new InvalidArgumentException("Validation rule $rule requires at least $count parameters."); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * The table must exist. |
| 67 | + * |
| 68 | + * @param string $table |
| 69 | + * @return void |
| 70 | + * |
| 71 | + * @throws PDOException |
| 72 | + */ |
| 73 | + public function requireTableExists($table) |
| 74 | + { |
| 75 | + if (! Schema::hasTable($table)) { |
| 76 | + throw new PDOException("Table $table not found."); |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments