-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathViolation.php
More file actions
119 lines (106 loc) · 2.89 KB
/
Copy pathViolation.php
File metadata and controls
119 lines (106 loc) · 2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?php
/**
* This file is part of the Vection package.
*
* (c) David M. Lung <vection@davidlung.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Vection\Component\Validator;
use JsonSerializable;
use Vection\Contracts\Validator\ViolationInterface;
/**
* Class Violation
*
* This class represents a violation of rules defined by a validator.
* Every time a validator failed validation, an object of this class
* will be created an returned. This class contains the information
* about the invalid value and an user message.
*
* @package Vection\Component\Validator
*/
class Violation implements ViolationInterface, JsonSerializable
{
protected mixed $value;
/** @var mixed[] */
protected array $constraints;
protected string $message;
protected string $result = '';
protected string $subject;
/**
* @param string $subject
* @param mixed $value
* @param mixed[] $constraints
* @param string $message
*/
public function __construct(string $subject, mixed $value, array $constraints, string $message)
{
$this->subject = $subject;
$this->value = $value;
$this->constraints = $constraints;
$this->message = $message;
}
/**
* @inheritDoc
*/
public function getValue(): mixed
{
return $this->value;
}
/**
* @inheritDoc
*/
public function getMessage(): string
{
if ( ! $this->result ) {
$constraints = ['{value}' => $this->valueToString($this->value)];
foreach ( $this->constraints as $name => $constraint ) {
$constraints['{'.$name.'}'] = $this->valueToString($constraint);
}
$this->result = str_replace(
array_keys($constraints),
array_values($constraints),
$this->message ?: ''
);
}
return $this->result;
}
/**
* @inheritDoc
*/
public function __toString(): string
{
return $this->getMessage();
}
/**
* @inheritDoc
*/
public function jsonSerialize(): mixed
{
return [
'property' => $this->subject,
'actual' => $this->value,
'message' => $this->getMessage()
];
}
/**
* Converts the given value into a string representation.
*
* @param mixed $value
*
* @return string
*/
private function valueToString(mixed $value): string
{
return match (gettype($value)) {
'integer', 'double', 'string' => (string)$value,
'boolean' => $value ? 'true' : 'false',
'NULL' => 'null',
'array' => 'Array',
'object' => 'Object',
default => '<unsupported-type>',
};
}
}