<?php
namespace App\InsuranceCompany\Bulins\SOAP\Subscriber;
use App\InsuranceCompany\Bulins\Exception\Exception;
use App\InsuranceCompany\Bulins\SOAP\Generated\Type\ErrorDescription;
use App\InsuranceCompany\Bulins\SOAP\Generated\Type\Result;
use App\InsuranceCompany\Common\Exception\NullValueException;
use App\InsuranceCompany\Common\Type\CustomResultInterface;
use App\InsuranceCompany\Common\Type\ResultProviderInterface;
use Phpro\SoapClient\Event\ResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use UnexpectedValueException;
/**
* Class ErrorHandlingSubscriber
*/
class ErrorHandlingSubscriber implements EventSubscriberInterface
{
/**
* @param ResponseEvent $event
* @throws Exception
* @throws NullValueException
*/
public function onClientResponse(ResponseEvent $event)
{
$response = $event->getResponse();
if (!($response instanceof ResultProviderInterface)) {
throw new UnexpectedValueException('Response type is not a result provider');
}
$result = $response->getResult();
if ($result === null) {
throw new NullValueException();
}
if (!($result instanceof Result)) {
if ($result instanceof CustomResultInterface) {
return;
}
throw new UnexpectedValueException('Result is not a subclass of Result');
}
$status = $result->getStatus();
switch ($status) {
case 'Error':
$errors = [];
foreach ($result->getErrors() as $errorDesc) {
/**
* @var ErrorDescription $errorDesc
*/
$name = $errorDesc->getPropertyName();
if (strlen($name) > 0) {
$errors[] = $name . ': ' . $errorDesc->getMessage();
} else {
$errors[] = $errorDesc->getMessage();
}
}
throw new Exception(
message: implode(PHP_EOL, $errors),
errors: $result->getErrors(),
);
case 'Success':
// nothing to do
break;
case 'None':
throw new UnexpectedValueException('Service returned status None');
default:
throw new UnexpectedValueException('Undefined status: ' . $status);
}
}
/**
* {@inheritdoc}
* @noinspection PhpArrayShapeAttributeCanBeAddedInspection
*/
public static function getSubscribedEvents(): array
{
return [
ResponseEvent::class => 'onClientResponse',
];
}
}