Completed
Push — develop ( b490de...9c223a )
by Maarten
02:17
created

Email   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 14
dl 0
loc 50
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A parseValue() 0 7 2
A parseLiteral() 0 7 2
A serialize() 0 3 1
1
<?php
2
3
namespace DeInternetJongens\LighthouseUtils\Schema\Scalars;
4
5
use Egulias\EmailValidator\EmailValidator;
6
use Egulias\EmailValidator\Validation\EmailValidation;
7
use Egulias\EmailValidator\Validation\RFCValidation;
8
use GraphQL\Error\Error;
9
use GraphQL\Language\AST\StringValueNode;
10
use GraphQL\Type\Definition\ScalarType;
11
12
/**
13
 * To validate e-mails we're using https://github.com/egulias/EmailValidator, this is a wrapper for the e-mail validation function provided by: http://isemail.info/
14
 * This package checks against RFC 5321 whereas `filter_var()` does not.
15
 */
16
class Email extends ScalarType
17
{
18
    /** @var string */
19
    public $name = 'Email';
20
21
    /** @var string */
22
    public $description = 'A valid RFC 5321 compliant e-mail.';
23
24
    /** @var EmailValidator */
25
    private $emailValidator;
26
27
    /** @var EmailValidation */
28
    private $validation;
29
30
    public function __construct()
31
    {
32
        $this->emailValidator = new EmailValidator();
33
        $this->validation = new RFCValidation();
34
    }
35
36
    /**
37
     * @inheritDoc
38
     */
39
    public function serialize($value)
40
    {
41
        return $value;
42
    }
43
44
    /**
45
     * @inheritDoc
46
     */
47
    public function parseValue($value)
48
    {
49
        if (! $this->emailValidator->isValid($value, $this->validation)) {
50
            throw new Error(sprintf('Input error: Expected valid e-mail, got: [%s]', $value));
51
        }
52
53
        return $value;
54
    }
55
56
    /**
57
     * @inheritDoc
58
     */
59
    public function parseLiteral($valueNode, array $variables = null)
60
    {
61
        if (! $valueNode instanceof StringValueNode) {
62
            throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, [$valueNode]);
63
        }
64
65
        return $this->parseValue($valueNode->value);
66
    }
67
}
68