Passed
Pull Request — master (#71)
by
unknown
03:43
created

RfCreditorReferenceGenerator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 1
c 1
b 0
f 1
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
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);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $generator->gener...this->reference, false) could return the type false which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
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
}