77 lines
2.5 KiB
PHP
77 lines
2.5 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace MonetaPhpShop\protocol;
|
||
|
||
use DOMDocument;
|
||
use DOMNode;
|
||
use MonetaPhpShop\Money;
|
||
use RuntimeException;
|
||
|
||
/**
|
||
* Ñáîðêà `MNT_RESPONSE` (`MONETA.Assistant.ru.pdf`, ãë. 4–5) — îáùàÿ ÷àñòü
|
||
* XML-îòâåòîâ Check URL è Pay URL: îáÿçàòåëüíûå ýëåìåíòû, ïîäïèñü è `MNT_ATTRIBUTES`.
|
||
*/
|
||
final class MntResponseXml
|
||
{
|
||
private function __construct() {}
|
||
|
||
/**
|
||
* @param Money|null $amount null — ñóììà íåèçâåñòíà (çàêàç íå íàéäåí), ýëåìåíò íå âûâîäèòñÿ
|
||
* @param array<string, string> $attributes ïàðû KEY -> VALUE äëÿ `MNT_ATTRIBUTES`, ñòðîêè â UTF-8
|
||
* @throws \DOMException
|
||
*/
|
||
public static function build(
|
||
string $accountId,
|
||
string $transactionId,
|
||
ResultCode $resultCode,
|
||
?Money $amount,
|
||
string $signature,
|
||
string $cms,
|
||
array $attributes = []
|
||
): string {
|
||
$document = new DOMDocument('1.0', 'UTF-8');
|
||
|
||
$response = $document->appendChild($document->createElement('MNT_RESPONSE'));
|
||
|
||
$elements = [
|
||
'MNT_ID' => $accountId,
|
||
'MNT_TRANSACTION_ID' => $transactionId,
|
||
'MNT_RESULT_CODE' => (string) $resultCode->getValue(),
|
||
'MNT_DESCRIPTION' => $resultCode->description(),
|
||
'MNT_AMOUNT' => $amount !== null ? $amount->toDecimal() : null,
|
||
'MNT_SIGNATURE' => $signature,
|
||
'MNT_CMS' => $cms,
|
||
];
|
||
foreach ($elements as $name => $value) {
|
||
if ($value !== null) {
|
||
self::text($document, $response, $name, $value);
|
||
}
|
||
}
|
||
|
||
if ($attributes !== []) {
|
||
$container = $response->appendChild($document->createElement('MNT_ATTRIBUTES'));
|
||
foreach ($attributes as $key => $value) {
|
||
$attribute = $container->appendChild($document->createElement('ATTRIBUTE'));
|
||
self::text($document, $attribute, 'KEY', (string) $key);
|
||
self::text($document, $attribute, 'VALUE', $value);
|
||
}
|
||
}
|
||
|
||
$xml = $document->saveXML();
|
||
if ($xml === false) {
|
||
throw new RuntimeException('Íå óäàëîñü ñåðèàëèçîâàòü MNT_RESPONSE.');
|
||
}
|
||
|
||
return $xml;
|
||
}
|
||
|
||
private static function text(DOMDocument $document, DOMNode $parent, string $name, string $value): void
|
||
{
|
||
$parent
|
||
->appendChild($document->createElement($name))
|
||
->appendChild($document->createTextNode($value));
|
||
}
|
||
}
|