Completed
Push — soap-12 ( 6e3908...80b930 )
by Asmir
26:02
created

Client::findFaultClass()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 2
1
<?php
2
namespace GoetasWebservices\SoapServices\SoapClient;
3
4
use GoetasWebservices\SoapServices\SoapClient\Arguments\ArgumentsReader;
5
use GoetasWebservices\SoapServices\SoapClient\Arguments\ArgumentsReaderInterface;
6
use GoetasWebservices\SoapServices\SoapClient\Arguments\Headers\Handler\HeaderHandler;
7
use GoetasWebservices\SoapServices\SoapClient\Envelope\SoapEnvelope\Messages\Fault as Fault11;
8
use GoetasWebservices\SoapServices\SoapClient\Envelope\SoapEnvelope12\Messages\Fault as Fault12;
9
use GoetasWebservices\SoapServices\SoapClient\Exception\ClientException;
10
use GoetasWebservices\SoapServices\SoapClient\Exception\ServerException;
11
use GoetasWebservices\SoapServices\SoapClient\Exception\SoapException;
12
use GoetasWebservices\SoapServices\SoapClient\Exception\UnexpectedFormatException;
13
use GoetasWebservices\SoapServices\SoapClient\Result\ResultCreator;
14
use GoetasWebservices\SoapServices\SoapClient\Result\ResultCreatorInterface;
15
use GoetasWebservices\SoapServices\SoapEnvelope;
16
use Http\Client\Exception\HttpException;
17
use Http\Client\HttpClient;
18
use Http\Message\MessageFactory;
19
use JMS\Serializer\Serializer;
20
use Psr\Http\Message\ResponseInterface;
21
22
class Client
23
{
24
    /**
25
     * @var Serializer
26
     */
27
    protected $serializer;
28
    /**
29
     * @var array
30
     */
31
    protected $serviceDefinition;
32
    /**
33
     * @var HttpClient
34
     */
35
    protected $client;
36
37
    /**
38
     * @var MessageFactory
39
     */
40
    protected $messageFactory;
41
42
    /**
43
     * @var ResultCreatorInterface
44
     */
45
    private $resultCreator;
46
47
    /**
48
     * @var ArgumentsReaderInterface
49
     */
50
    private $argumentsReader;
51 30
52
53 30
    public function __construct(array $serviceDefinition, Serializer $serializer, MessageFactory $messageFactory, HttpClient $client, HeaderHandler $headerHandler)
54 30
    {
55
        $this->serviceDefinition = $serviceDefinition;
56 30
        $this->serializer = $serializer;
57 30
58 30
        $this->client = $client;
59 30
        $this->messageFactory = $messageFactory;
60 30
        $this->argumentsReader = new ArgumentsReader($this->serializer, $headerHandler);
61
        $this->resultCreator = new ResultCreator($this->serializer, !empty($serviceDefinition['unwrap']));
62 28
    }
63
64 28
    public function __call($functionName, array $args)
65 28
    {
66
        $soapOperation = $this->findOperation($functionName, $this->serviceDefinition);
67 28
        $message = $this->argumentsReader->readArguments($args, $soapOperation['input']);
68 28
69 28
        $xmlMessage = $this->serializer->serialize($message, 'xml');
0 ignored issues
show
Bug introduced by
It seems like $message defined by $this->argumentsReader->...soapOperation['input']) on line 67 can also be of type null; however, JMS\Serializer\Serializer::serialize() does only seem to accept object|array|integer|double|string|boolean, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
70
        $headers = $this->buildHeaders($soapOperation);
71
        $request = $this->messageFactory->createRequest('POST', $this->serviceDefinition['endpoint'], $headers, $xmlMessage);
72 28
73 18
        try {
74 2
            $response = $this->client->sendRequest($request);
75 2
            if (strpos($response->getHeaderLine('Content-Type'), 'xml') === false) {
76 2
                throw new UnexpectedFormatException(
77 2
                    $response,
78 2
                    $request,
79
                    "Unexpected content type '" . $response->getHeaderLine('Content-Type') . "'"
80
                );
81
            }
82 16
83 4
            // fast return if no return is expected
84
            if (!count($soapOperation['output']['parts'])) {
85
                return null;
86 12
            }
87 12
88
            $body = (string)$response->getBody();
89
90
            $faultClass = $this->findFaultClass($response);
91
92
            if (strpos($body, ':Fault>') !== false) { // some server returns a fault with 200 OK HTTP
93
                $fault = $this->serializer->deserialize($body, $faultClass, 'xml');
94
                throw $fault->createException($response, $request);
95
            }
96
97
            $response = $this->serializer->deserialize($body, $soapOperation['output']['message_fqcn'], 'xml');
98
        } catch (HttpException $e) {
99 12
            if (strpos($e->getResponse()->getHeaderLine('Content-Type'), 'xml') !== false) {
100 24
                $faultClass = $this->findFaultClass($e->getResponse());
101
                $fault = $this->serializer->deserialize((string)$e->getResponse()->getBody(), $faultClass, 'xml');
102 10
                throw $fault->createException($e->getResponse(), $e->getRequest(), $e);
103 7
            } else {
104 6
                throw new ServerException(
105 6
                    $e->getResponse(),
106 6
                    $e->getRequest(),
107 6
                    $e
108 6
                );
109 6
            }
110
        }
111 6
        return $this->resultCreator->prepareResult($response, $soapOperation['output']);
112
    }
113 4
114 4
    public function findFaultClass(ResponseInterface $response)
115 4
    {
116 4
        if (strpos($response->getHeaderLine('Content-Type'), 'application/soap+xml') === 0) {
117 4
            return Fault12::class;
118
        } else {
119 4
            return Fault11::class;
120
        }
121
    }
122 12
123
    protected function buildHeaders(array $operation)
124
    {
125 28
        return [
126
            'Content-Type' => isset($operation['version']) && $operation['version'] === '1.2'
127
                ? 'application/soap+xml; charset=utf-8'
128 28
                : 'text/xml; charset=utf-8',
129 28
            'SoapAction' => '"' . $operation['action'] . '"',
130 28
        ];
131 28
    }
132 28
133
    protected function findOperation($functionName, array $serviceDefinition)
134
    {
135 28
        if (isset($serviceDefinition['operations'][$functionName])) {
136
            return $serviceDefinition['operations'][$functionName];
137 28
        }
138 28
139
        foreach ($serviceDefinition['operations'] as $opName => $operation) {
140
            if (strtolower($functionName) == strtolower($opName)) {
141
                return $operation;
142
            }
143
        }
144
        throw new ClientException("Can not find an operation to run $functionName service call");
145
    }
146
}
147