forked from olegkrivtsov/using-zf3-book-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserExistsValidator.php
More file actions
88 lines (75 loc) · 2.33 KB
/
UserExistsValidator.php
File metadata and controls
88 lines (75 loc) · 2.33 KB
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
<?php
namespace ProspectOne\UserModule\Validator;
use Zend\Validator\AbstractValidator;
/**
* This validator class is designed for checking if there is an existing user
* with such an email.
*/
class UserExistsValidator extends AbstractValidator
{
/**
* Available validator options.
* @var array
*/
protected $options = array(
'entityManager' => null,
'user' => null
);
// Validation failure message IDs.
const NOT_SCALAR = 'notScalar';
const USER_EXISTS = 'userExists';
/**
* Validation failure messages.
* @var array
*/
protected $messageTemplates = array(
self::NOT_SCALAR => "The email must be a scalar value",
self::USER_EXISTS => "Another user with such an email already exists"
);
/**
* Constructor.
*/
public function __construct($options = null)
{
// Set filter options (if provided).
if(is_array($options)) {
if(isset($options['entityManager']))
$this->options['entityManager'] = $options['entityManager'];
if(isset($options['user']))
$this->options['user'] = $options['user'];
}
// Call the parent class constructor
parent::__construct($options);
}
/**
* Check if user exists.
*/
public function isValid($value)
{
if(!is_scalar($value)) {
$this->error(self::NOT_SCALAR);
return false;
}
// Get Doctrine entity manager.
$entityManager = $this->options['entityManager'];
if (!empty($this->options['user'])) {
$user = $entityManager->getRepository(get_class($this->options['user']))->findOneByEmail($value);
} else {
$user = null;
}
if($this->options['user']==null) {
$isValid = ($user==null);
} else {
if($this->options['user']->getEmail()!=$value && $user!=null)
$isValid = false;
else
$isValid = true;
}
// If there were an error, set error message.
if(!$isValid) {
$this->error(self::USER_EXISTS);
}
// Return validation result.
return $isValid;
}
}