ConstraintException::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 2
crap 1
1
<?php
2
3
/*
4
 * This file is part of the JVal package.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace JVal\Exception;
11
12
use JVal\Context;
13
14
/**
15
 * Base class for constraint exceptions.
16
 */
17
abstract class ConstraintException extends \Exception
18
{
19
    /**
20
     * @var Context
21
     */
22
    private $context;
23
24
    /**
25
     * @var mixed
26
     */
27
    private $target;
28
29
    /**
30
     * Constructor.
31
     *
32
     * @param Context $context The current validation context
33
     * @param mixed   $target  An optional exception target not
34
     *                         present in the current context
35
     */
36 61
    public function __construct(Context $context, $target = null)
37
    {
38 61
        parent::__construct();
39 61
        $this->context = $context;
40 61
        $this->target = $target;
41 61
        $this->buildMessage();
42 61
    }
43
44
    /**
45
     * @return string
46
     */
47 61
    public function getPath()
48
    {
49 61
        return $this->context->getCurrentPath();
50
    }
51
52
    /**
53
     * @return mixed
54
     */
55 59
    public function getTarget()
56
    {
57 59
        return $this->target;
58
    }
59
60
    /**
61
     * Builds the exception message.
62
     */
63
    abstract protected function buildMessage();
64
65
    /**
66
     * Returns a printable representation of the exception
67
     * target. If no target has been explicitly passed in,
68
     * the last non-array segments of the path are returned.
69
     *
70
     * @return string
71
     */
72 59
    protected function getTargetNode()
73
    {
74 59
        if (null === $target = $this->getTarget()) {
75 57
            $segments = explode('/', $this->getPath());
76 57
            $target = '';
77
78 57
            while (count($segments) > 0) {
79 57
                $segment = array_pop($segments);
80 57
                $target = $segment.'/'.$target;
81
82 57
                if (!is_numeric($segment)) {
83 57
                    break;
84
                }
85 8
            }
86
87 57
            return rtrim($target, '/');
88
        }
89
90 2
        return $target;
91
    }
92
}
93