RequestSigner::sign()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 35
ccs 19
cts 19
cp 1
rs 9.36
c 0
b 0
f 0
cc 3
nc 3
nop 5
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Bip70\X509;
6
7
use Bip70\Protobuf\Codec\NonDiscardingBinaryCodec;
8
use Bip70\Protobuf\Proto\PaymentDetails;
9
use Bip70\Protobuf\Proto\PaymentRequest;
10
use Bip70\Protobuf\Proto\X509Certificates;
11
use Sop\CryptoBridge\Crypto;
12
use Sop\CryptoTypes\AlgorithmIdentifier\Feature\AsymmetricCryptoAlgorithmIdentifier;
13
use Sop\CryptoTypes\Asymmetric\PrivateKeyInfo;
14
use X509\Certificate\Certificate;
15
use X509\Certificate\CertificateBundle;
16
17
class RequestSigner implements RequestSignerInterface
18
{
19
    /**
20
     * @var Crypto
21
     */
22
    private $crypto;
23
24
    /**
25
     * RequestSigner constructor.
26
     * @param Crypto|null $crypto
27
     */
28 6
    public function __construct(Crypto $crypto = null)
29
    {
30 6
        $this->crypto = $crypto ?: Crypto::getDefault();
31 6
    }
32
33
    /**
34
     * @inheritdoc
35
     */
36 6
    public function sign(
37
        PaymentDetails $details,
38
        string $pkiType,
39
        PrivateKeyInfo $privateKey,
40
        Certificate $cert,
41
        CertificateBundle $intermediates
42
    ): PaymentRequest {
43 6
        if ($pkiType === PKIType::NONE) {
44 1
            throw new \UnexpectedValueException("Don't call sign with pki_type = none");
45
        }
46
47
        /** @var AsymmetricCryptoAlgorithmIdentifier $algOid */
48 5
        $algOid = $privateKey->algorithmIdentifier();
49 5
        $signAlgorithm = SignatureAlgorithmFactory::getSignatureAlgorithm($pkiType, $algOid);
50
51 4
        $x509Certs = new X509Certificates();
52 4
        $x509Certs->setCertificate($cert->toDER(), 0);
53 4
        foreach ($intermediates as $i => $intermediate) {
54 3
            $x509Certs->setCertificate($intermediate->toDER(), $i + 1);
55
        }
56
57 4
        $request = new PaymentRequest();
58 4
        $request->setPaymentDetailsVersion(1);
59 4
        $request->setPkiType($pkiType);
60 4
        $request->setPkiData($x509Certs->serialize());
61 4
        $request->setSerializedPaymentDetails($details->serialize());
62 4
        $request->setSignature('');
63
64 4
        $data = $request->serialize(new NonDiscardingBinaryCodec());
65 4
        $signature = $this->crypto->sign($data, $privateKey, $signAlgorithm);
66
67 4
        $request->setSignature($signature->bitString()->string());
68
69 4
        return $request;
70
    }
71
}
72