1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the PHALCON-EXT package. |
5
|
|
|
* |
6
|
|
|
* (c) Jitendra Adhikari <[email protected]> |
7
|
|
|
* <https://github.com/adhocore> |
8
|
|
|
* |
9
|
|
|
* Licensed under MIT license. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace PhalconExt\Validation; |
13
|
|
|
|
14
|
|
|
use Phalcon\Validation; |
|
|
|
|
15
|
|
|
use Phalcon\Validation\Message; |
|
|
|
|
16
|
|
|
use Phalcon\Validation\Validator; |
|
|
|
|
17
|
|
|
use PhalconExt\Di\ProvidesDi; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Check that a field exists in the related table. |
21
|
|
|
* |
22
|
|
|
* @author Jitendra Adhikari <[email protected]> |
23
|
|
|
* @license MIT |
24
|
|
|
* |
25
|
|
|
* @link https://github.com/adhocore/phalcon-ext |
26
|
|
|
*/ |
27
|
|
|
class Existence extends Validator |
28
|
|
|
{ |
29
|
|
|
use ProvidesDi; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Executes the validation. |
33
|
|
|
* |
34
|
|
|
* @param validation $validation |
35
|
|
|
* @param string $field |
36
|
|
|
*/ |
37
|
|
|
public function validate(Validation $validation, $field): bool |
38
|
|
|
{ |
39
|
|
|
$options = $this->_options + [ |
40
|
|
|
'table' => $field, |
41
|
|
|
'column' => isset($this->_options['table']) ? $field : 'id', |
42
|
|
|
]; |
43
|
|
|
|
44
|
|
|
$count = $this->di('db')->countBy($options['table'], [ |
45
|
|
|
$options['column'] => $validation->getValue($field), |
46
|
|
|
]); |
47
|
|
|
|
48
|
|
|
if ($count > 0) { |
49
|
|
|
return true; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return $this->failed($validation, $field); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Set message when valdiation failed. |
57
|
|
|
* |
58
|
|
|
* @param Validation $validation |
59
|
|
|
* @param string $field |
60
|
|
|
* |
61
|
|
|
* @return bool |
62
|
|
|
*/ |
63
|
|
|
protected function failed(Validation $validation, $field): bool |
64
|
|
|
{ |
65
|
|
|
$label = $this->getOption('label') ?: $validation->getLabel($field); |
66
|
|
|
$error = $this->getOption('message') ?: $validation->getDefaultMessage('Existence'); |
67
|
|
|
$error = \strtr($error, [':field' => $label]); |
68
|
|
|
|
69
|
|
|
$validation->appendMessage( |
70
|
|
|
new Message($error, $field, 'Existence', $this->getOption('code')) |
71
|
|
|
); |
72
|
|
|
|
73
|
|
|
return false; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
Let?s assume that you have a directory layout like this:
and let?s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: