ContainsValidUrlsValidator::validate()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5.025

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 5
eloc 9
c 1
b 0
f 1
nc 4
nop 2
dl 0
loc 19
ccs 9
cts 10
cp 0.9
crap 5.025
rs 9.6111
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