Passed
Push — master ( c62146...3b79d8 )
by Mauro
02:20
created

UserValidation::validateEmail()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace App\Validation;
4
5
use App\Message\UserMessage;
6
use Respect\Validation\Validator as v;
7
8
/**
9
 * User Validation.
10
 */
11
abstract class UserValidation
12
{
13
    /**
14
     * Validate and sanitize a username.
15
     *
16
     * @param string $name
17
     * @return string
18
     * @throws \Exception
19
     */
20 View Code Duplication
    protected static function validateName($name)
21
    {
22
        if (!v::alnum()->length(2, 100)->validate($name)) {
23
            throw new \Exception(UserMessage::USER_NAME_INVALID, 400);
24
        }
25
26
        return $name;
27
    }
28
29
    /**
30
     * Validate and sanitize a email address.
31
     *
32
     * @param string $emailValue
33
     * @return string
34
     * @throws \Exception
35
     */
36
    protected static function validateEmail($emailValue)
37
    {
38
        $email = filter_var($emailValue, FILTER_SANITIZE_EMAIL);
39
        if (!v::email()->validate($email)) {
40
            throw new \Exception(UserMessage::USER_EMAIL_INVALID, 400);
41
        }
42
43
        return $email;
44
    }
45
46
    /**
47
     * Validate and sanitize input data when create new user.
48
     *
49
     * @param array $input
50
     * @return string
51
     * @throws \Exception
52
     */
53
    public static function validateInputOnCreateUser($input)
54
    {
55
        if (!isset($input['name'])) {
56
            throw new \Exception(UserMessage::USER_NAME_REQUIRED, 400);
57
        }
58
        $name = self::validateName($input['name']);
59
        $email = null;
60
        if (isset($input['email'])) {
61
            $email = self::validateEmail($input['email']);
62
        }
63
64
        return ['name' => $name, 'email' => $email];
65
    }
66
67
    /**
68
     * Validate and sanitize input data when update a user.
69
     *
70
     * @param array $input
71
     * @param object $user
72
     * @return string
73
     * @throws \Exception
74
     */
75
    public static function validateInputOnUpdateUser($input, $user)
76
    {
77
        if (!isset($input['name']) && !isset($input['email'])) {
78
            throw new \Exception(UserMessage::USER_INFO_REQUIRED, 400);
79
        }
80
        $name = $user->name;
81
        if (isset($input['name'])) {
82
            $name = self::validateName($input['name']);
83
        }
84
        $email = $user->email;
85
        if (isset($input['email'])) {
86
            $email = self::validateEmail($input['email']);
87
        }
88
89
        return ['name' => $name, 'email' => $email];
90
    }
91
}
92