PatternRule::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
namespace Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\Mapping;
3
4
use Boekkooi\Bundle\JqueryValidationBundle\Exception\LogicException;
5
use Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\ConstraintRule;
6
use Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\ConstraintMapperInterface;
7
use Boekkooi\Bundle\JqueryValidationBundle\Form\RuleCollection;
8
use Boekkooi\Bundle\JqueryValidationBundle\Form\RuleMessage;
9
use Symfony\Component\Form\FormInterface;
10
use Symfony\Component\Validator\Constraint;
11
use Symfony\Component\Validator\Constraints\Regex;
12
13
/**
14
 * @author Warnar Boekkooi <[email protected]>
15
 */
16
class PatternRule implements ConstraintMapperInterface
17
{
18
    const RULE_NAME = 'pattern';
19
20
    /**
21
     * @var bool
22
     */
23
    private $enabled;
24
25
    public function __construct($enabled)
26
    {
27
        $this->enabled = $enabled;
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function resolve(Constraint $constraint, FormInterface $form, RuleCollection $collection)
34
    {
35
        if (!$this->supports($constraint, $form)) {
36
            throw new LogicException();
37
        }
38
39
        /** @var \Symfony\Component\Validator\Constraints\Regex $constraint */
40
        $collection->set(
41
            self::RULE_NAME,
42
            new ConstraintRule(
43
                self::RULE_NAME,
44
                $constraint->getHtmlPattern(),
45
                new RuleMessage($constraint->message),
46
                $constraint->groups
47
            )
48
        );
49
    }
50
51
    public function supports(Constraint $constraint, FormInterface $form)
52
    {
53
        return $this->enabled && get_class($constraint) === Regex::class;
54
    }
55
}
56