MysqlEncryptionServiceProvider::addValidators()   A
last analyzed

Complexity

Conditions 4
Paths 1

Size

Total Lines 31
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 2 Features 2
Metric Value
cc 4
eloc 13
c 6
b 2
f 2
nc 1
nop 0
dl 0
loc 31
rs 9.8333
1
<?php
2
3
namespace IonGhitun\MysqlEncryption;
4
5
use Exception;
6
use Illuminate\Support\Facades\DB;
7
use Illuminate\Support\Facades\Validator;
8
use Illuminate\Support\ServiceProvider;
9
10
/**
11
 *
12
 */
13
class MysqlEncryptionServiceProvider extends ServiceProvider
14
{
15
    /**
16
     * @return void
17
     */
18
    public function boot(): void
19
    {
20
        $this->addValidators();
21
    }
22
23
    /**
24
     * @return void
25
     */
26
    private function addValidators(): void
27
    {
28
        /**
29
         * Validate unique binary encrypted
30
         */
31
        Validator::extend('unique_encrypted', function ($attribute, $value, array $parameters) {
32
            if (!isset($parameters[0])) {
33
                throw new Exception('unique_encrypted requires at least one parameter');
34
            }
35
36
            $field = $parameters[1] ?? $attribute;
37
            $ignore = $parameters[2] ?? null;
38
39
            $items = DB::select("SELECT count(*) as aggregate FROM `" . $parameters[0] . "` WHERE AES_DECRYPT(`" . $field . "`, '" . getenv("ENCRYPTION_KEY") . "') LIKE " . DB::getPdo()->quote($value) . " COLLATE utf8mb4_general_ci" . ($ignore ? " AND id != " . $ignore : ''));
40
41
            return $items[0]->aggregate === 0;
42
        });
43
44
        /**
45
         * Validate exists binary encrypted
46
         */
47
        Validator::extend('exists_encrypted', function ($attribute, $value, array $parameters) {
48
            if (!isset($parameters[0])) {
49
                throw new Exception('exists_encrypted requires at least one parameter');
50
            }
51
52
            $field = $parameters[1] ?? $attribute;
53
54
            $items = DB::select("SELECT count(*) as aggregate FROM `" . $parameters[0] . "` WHERE AES_DECRYPT(`" . $field . "`, '" . getenv("ENCRYPTION_KEY") . "') LIKE " . DB::getPdo()->quote($value) . " COLLATE utf8mb4_general_ci");
55
56
            return $items[0]->aggregate > 0;
57
        });
58
    }
59
60
    /**
61
     * @return void
62
     */
63
    public function register()
64
    {
65
    }
66
}
67