|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @author Muhammed Akbulut <[email protected]> |
|
4
|
|
|
* @copyright Zicht Online <http://www.zicht.nl> |
|
5
|
|
|
*/ |
|
6
|
|
|
|
|
7
|
|
|
namespace Zicht\Bundle\UrlBundle\Validator\Constraints; |
|
8
|
|
|
|
|
9
|
|
|
use Symfony\Component\Validator\Constraint; |
|
10
|
|
|
use Symfony\Component\Validator\ConstraintValidator; |
|
11
|
|
|
use Zicht\Bundle\UrlBundle\Service\UrlValidator; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Class ContainsValidUrlsValidator |
|
15
|
|
|
* |
|
16
|
|
|
* @package Zicht\Bundle\UrlBundle\Validator\Constraints |
|
17
|
|
|
*/ |
|
18
|
|
|
class ContainsValidUrlsValidator extends ConstraintValidator |
|
19
|
|
|
{ |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @var UrlValidator |
|
23
|
|
|
*/ |
|
24
|
|
|
private $urlValidator; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* ContainsValidUrlsValidator constructor. |
|
28
|
|
|
* |
|
29
|
|
|
* @param UrlValidator $urlValidator |
|
30
|
|
|
*/ |
|
31
|
4 |
|
public function __construct(UrlValidator $urlValidator) |
|
32
|
|
|
{ |
|
33
|
4 |
|
$this->urlValidator = $urlValidator; |
|
34
|
4 |
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Checks if the passed value is valid. |
|
38
|
|
|
* Validates only urls within a href's |
|
39
|
|
|
* |
|
40
|
|
|
* @param mixed $value The value that should be validated |
|
41
|
|
|
* @param Constraint $constraint The constraint for the validation |
|
42
|
|
|
*/ |
|
43
|
4 |
|
public function validate($value, Constraint $constraint) |
|
44
|
|
|
{ |
|
45
|
|
|
// collect urls |
|
46
|
4 |
|
$matches = array(); |
|
47
|
|
|
|
|
48
|
|
|
// matches all urls withing a href's |
|
49
|
4 |
|
preg_match_all("#<a\s+(?:[^>]*?\s+)?href=\"((https*:)*//[^\"]*)\">.*</a>#U", $value, $matches); |
|
50
|
|
|
|
|
51
|
4 |
|
if (count($matches) === 0 || !isset($matches[1])) { |
|
52
|
|
|
return; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
4 |
|
$externalUrls = $matches[1]; |
|
56
|
|
|
|
|
57
|
|
|
// validate urls |
|
58
|
4 |
|
foreach ($externalUrls as $externalUrl) { |
|
59
|
4 |
|
if ($this->urlValidator->validate($externalUrl) === false) { |
|
60
|
2 |
|
$this->context |
|
61
|
4 |
|
->addViolation($constraint->message, ['%string%' => $externalUrl]); |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
4 |
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|