<?php declare(strict_types=1);
namespace Uandi\UandiEfbErpSynchronization\Service\Api;
use Exception;
use Monolog\Logger;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use SoapFault;
use Uandi\UandiEfbErpSynchronization\Service\Api\SoapClient as SoapClient;
use Uandi\UandiEfbErpSynchronization\Service\ApiConnectionServiceInterface;
class SoapService implements ApiConnectionServiceInterface
{
private SystemConfigService $systemConfigService;
private Logger $logger;
public function __construct(SystemConfigService $systemConfigService, Logger $logger) {
$this->systemConfigService = $systemConfigService;
$this->logger = $logger;
}
/**
* Execute soap request
*
* @param array $request
* @param string|null $requestName
* @param string|null $salesChannelId
* @return array
*/
public function execute(array $request = [], ?string $requestName = null, ?string $salesChannelId = null): array
{
try {
//encode the request array
$jsonRequest = json_encode($request);
// create ERP request
$client = $this->createConnection($salesChannelId);
$jsonResponse = $client->$requestName(["request_p" => $jsonRequest]);
$returnValue = $jsonResponse->return_value;
$responseArray = $this->jsonDecode($returnValue);
// handle/log the error response
if (isset($responseArray['error'])) {
$this->logger->critical(
sprintf(
'%s: Request name: %s, Error code: %s, Error text: %s',
__METHOD__,
$requestName,
$responseArray['error']['error_code'],
$responseArray['error']['error_text']
)
);
return ['request' => $request];
}
$responseArray['request'] = $request;
return $responseArray;
} catch (Exception $e) {
$this->logger->critical(
sprintf(
'%s, %s: %s, trace: %s',
$request['customer_number'] ?? '',
__METHOD__,
$e->getMessage(),
$e->getTraceAsString()
)
);
return ['request' => $request];
}
}
/**
* Create connection to the ERP
*
* @param string|null $salesChannelId
* @return SoapClient
* @throws SoapFault
*/
private function createConnection(?string $salesChannelId = null): SoapClient
{
$wsdl = $this->systemConfigService->get('UandiEfbErpSynchronization.config.soapApiEndpoint', $salesChannelId);
$user = $this->systemConfigService->get('UandiEfbErpSynchronization.config.soapApiUsername', $salesChannelId);
$password = $this->systemConfigService->get('UandiEfbErpSynchronization.config.soapApiPassword', $salesChannelId);
return new SoapClient(
$wsdl,
array('user' => $user, 'password' => $password)
);
}
/**
* Decodes json
*
* @param $json
*
* @return array
*/
public function jsonDecode($json): array
{
$data = json_decode($json, true);
if (JSON_ERROR_NONE !== json_last_error()) {
$errorMessage['message'] = 'JSON is invalid';
$errorMessage['json_last_error_msg'] = json_last_error_msg();
$errorMessage['json'] = $json;
$this->logger->critical(sprintf('%s: error %s', __METHOD__, json_encode($errorMessage, JSON_PRETTY_PRINT)));
}
return $data === null ? [] : $data;
}
}