/
EmailValidator.php
89 lines (70 loc) · 2.65 KB
/
EmailValidator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
namespace Symfony\Component\Validator\Constraints;
/*
* This file is part of the Symfony framework.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class EmailValidator extends ConstraintValidator
{
const PATTERN = '/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i';
public function isValid($value, Constraint $constraint)
{
if ($value === null || $value === '') {
return true;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) {
throw new UnexpectedTypeException($value, 'string');
}
$value = (string)$value;
if (!preg_match(self::PATTERN, $value)) {
$this->setMessage($constraint->message, array('{{ value }}' => $value));
return false;
}
if ($constraint->checkMX) {
$host = substr($value, strpos($value, '@') + 1);
if (!$this->checkMX($host)) {
$this->setMessage($constraint->message, array('{{ value }}' => $value));
return false;
}
}
return true;
}
/**
* Check DNA Records for MX type (from Doctrine EmailValidator).
*
* @param string $host Host name
*
* @return boolean
*
* @licence This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.phpdoctrine.org>.
*/
private function checkMX($host)
{
// We have different behavior here depending of OS and PHP version
if (strtolower(substr(PHP_OS, 0, 3)) === 'win' && version_compare(PHP_VERSION, '5.3.0', '<')) {
$output = array();
@exec('nslookup -type=MX '.escapeshellcmd($host) . ' 2>&1', $output);
if (empty($output)) {
throw new ValidatorError('Unable to execute DNS lookup. Are you sure PHP can call exec()?');
}
foreach ($output as $line) {
if (preg_match('/^'.$host.'/', $line)) {
return true;
}
}
return false;
} else if (function_exists('checkdnsrr')) {
return checkdnsrr($host, 'MX');
}
throw new ValidatorError('Could not retrieve DNS record information. Remove check_mx = true to prevent this warning');
}
}