Files
alfa-bank-sdk/src/Traits/SignableData.php
Anatoliy Poloz 706fcb01b2 fix
2026-03-08 18:03:43 +03:00

49 lines
1.9 KiB
PHP

<?php
declare(strict_types=1);
namespace Apoloz\AlfaBank\Traits;
use Apoloz\AlfaBank\Contracts\SignerInterface;
use Apoloz\AlfaBank\Data\NominalAccounts\Payouts\DigestSignatureData;
use Spatie\LaravelData\DataCollection;
trait SignableData
{
public function sign(SignerInterface $signer): self
{
// 1. Create a clone to represent the data-to-be-signed (without existing signatures)
$clone = clone $this;
// We explicitly set digestSignatures to null or empty for the signature calculation
// assuming the bank expects the "business payload" only.
// If the bank expects the field "digestSignatures": [] to be present in signed string,
// we should initialize it as empty collection.
// Based on common practices, we exclude it or keep it null.
// Let's assume we exclude it (set to null if the property is nullable).
$clone->digestSignatures = null;
// 2. Serialize to JSON
// We use JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES to match typical API expectations
$jsonToSign = $clone->toJson(JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
// 3. Sign
$signature = $signer->sign($jsonToSign);
// 4. Attach signature to the original object
if ($this->digestSignatures === null) {
$this->digestSignatures = new DataCollection(DigestSignatureData::class, []);
}
// We can't push to DataCollection directly if it's not array-access compatible in all versions,
// but Spatie DataCollection is usually iterable.
// Safest way is to reconstruct it.
$current = array_values($this->digestSignatures->toCollection()->all());
$current[] = new DigestSignatureData($signature, 'cms');
$this->digestSignatures = new DataCollection(DigestSignatureData::class, $current);
return $this;
}
}