1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sprain\SwissQrBill\Reference; |
4
|
|
|
|
5
|
|
|
use kmukku\phpIso11649\phpIso11649; |
6
|
|
|
use Sprain\SwissQrBill\String\StringModifier; |
7
|
|
|
use Sprain\SwissQrBill\Validator\Exception\InvalidCreditorReferenceException; |
8
|
|
|
use Sprain\SwissQrBill\Validator\SelfValidatableInterface; |
9
|
|
|
use Sprain\SwissQrBill\Validator\SelfValidatableTrait; |
10
|
|
|
use Symfony\Component\Validator\Constraints as Assert; |
11
|
|
|
use Symfony\Component\Validator\Mapping\ClassMetadata; |
12
|
|
|
|
13
|
|
|
class RfCreditorReferenceGenerator implements SelfValidatableInterface |
14
|
|
|
{ |
15
|
|
|
use SelfValidatableTrait; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var string |
19
|
|
|
*/ |
20
|
|
|
protected $reference; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Transform a string to a valid CreditorReference. |
24
|
|
|
* |
25
|
|
|
* @param string $reference |
26
|
|
|
* @return string |
27
|
|
|
* @throws \Exception |
28
|
|
|
*/ |
29
|
|
|
public static function generate(string $reference) : string |
30
|
|
|
{ |
31
|
|
|
$generator = new self($reference); |
32
|
|
|
|
33
|
|
|
return $generator->doGenerate(); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* RfCreditorReferenceGenerator constructor. |
38
|
|
|
* |
39
|
|
|
* @param $reference |
40
|
|
|
*/ |
41
|
|
|
public function __construct(string $reference) |
42
|
|
|
{ |
43
|
|
|
$this->reference = StringModifier::stripWhitespace($reference); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Run the generator. |
48
|
|
|
* |
49
|
|
|
* @return string |
50
|
|
|
* @throws \Exception |
51
|
|
|
*/ |
52
|
|
|
public function doGenerate() : string |
53
|
|
|
{ |
54
|
|
|
if (!$this->isValid()) { |
55
|
|
|
throw new InvalidCreditorReferenceException( |
56
|
|
|
'The provided data is not valid to generate a creditor reference. Use getViolations() to find details.' |
57
|
|
|
); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$generator = new phpIso11649(); |
61
|
|
|
|
62
|
|
|
return $generator->generateRfReference($this->reference, false); |
|
|
|
|
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* {@inheritDoc} |
67
|
|
|
*/ |
68
|
|
|
public static function loadValidatorMetadata(ClassMetadata $metadata): void |
69
|
|
|
{ |
70
|
|
|
$metadata->addPropertyConstraints('reference', [ |
71
|
|
|
new Assert\Regex([ |
72
|
|
|
'pattern' => '~^[a-zA-Z0-9]*$~', |
73
|
|
|
'match' => true |
74
|
|
|
]), |
75
|
|
|
new Assert\Length([ |
76
|
|
|
'min' => 1, |
77
|
|
|
'max' => 21 // 25 - 'RF' - CheckSum |
78
|
|
|
]), |
79
|
|
|
new Assert\NotBlank() |
80
|
|
|
]); |
81
|
|
|
} |
82
|
|
|
} |