Completed
Pull Request — master (#34)
by
unknown
03:09
created

Client::__call()   B

Complexity

Conditions 6
Paths 22

Size

Total Lines 49

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 31
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 49
ccs 31
cts 31
cp 1
rs 8.4905
c 0
b 0
f 0
cc 6
nc 22
nop 2
crap 6
1
<?php
2
3
namespace GoetasWebservices\SoapServices\SoapClient;
4
5
use GoetasWebservices\SoapServices\SoapClient\Arguments\ArgumentsReader;
6
use GoetasWebservices\SoapServices\SoapClient\Arguments\ArgumentsReaderInterface;
7
use GoetasWebservices\SoapServices\SoapClient\Arguments\Headers\Handler\HeaderHandler;
8
use GoetasWebservices\SoapServices\SoapClient\Envelope\SoapEnvelope\Messages\Fault as Fault11;
9
use GoetasWebservices\SoapServices\SoapClient\Envelope\SoapEnvelope12\Messages\Fault as Fault12;
10
use GoetasWebservices\SoapServices\SoapClient\Exception\ClientException;
11
use GoetasWebservices\SoapServices\SoapClient\Exception\ServerException;
12
use GoetasWebservices\SoapServices\SoapClient\Exception\SoapException;
13
use GoetasWebservices\SoapServices\SoapClient\Exception\UnexpectedFormatException;
14
use GoetasWebservices\SoapServices\SoapClient\Result\ResultCreator;
15
use GoetasWebservices\SoapServices\SoapClient\Result\ResultCreatorInterface;
16
use GoetasWebservices\SoapServices\SoapEnvelope;
17
use Http\Client\Exception\HttpException;
18
use Http\Client\HttpClient;
19
use Http\Message\MessageFactory;
20
use JMS\Serializer\Serializer;
21
use Psr\Http\Message\ResponseInterface;
22
use Psr\Http\Message\RequestInterface;
23
24
class Client
25
{
26
    /**
27
     * @var Serializer
28
     */
29
    protected $serializer;
30
    /**
31
     * @var array
32
     */
33
    protected $serviceDefinition;
34
    /**
35
     * @var HttpClient
36
     */
37
    protected $client;
38
39
    /**
40
     * @var MessageFactory
41
     */
42
    protected $messageFactory;
43
44
    /**
45
     * @var ResultCreatorInterface
46
     */
47
    private $resultCreator;
48
49
    /**
50
     * @var ArgumentsReaderInterface
51
     */
52
    private $argumentsReader;
53
54
    /**
55
     * @var RequestInterface
56
     */
57
    private $requestMessage;
58
59
    /**
60
     * @var ResponseInterface
61
     */
62
    private $responseMessage;
63
64
65 32
    public function __construct(array $serviceDefinition, Serializer $serializer, MessageFactory $messageFactory, HttpClient $client, HeaderHandler $headerHandler)
66
    {
67 32
        $this->serviceDefinition = $serviceDefinition;
68 32
        $this->serializer = $serializer;
69
70 32
        $this->client = $client;
71 32
        $this->messageFactory = $messageFactory;
72 32
        $this->argumentsReader = new ArgumentsReader($this->serializer, $headerHandler);
73 32
        $this->resultCreator = new ResultCreator($this->serializer, !empty($serviceDefinition['unwrap']));
74 32
    }
75
76 30
    public function __call($functionName, array $args)
77
    {
78 30
        $soapOperation = $this->findOperation($functionName, $this->serviceDefinition);
79 30
        $message = $this->argumentsReader->readArguments($args, $soapOperation['input']);
80
81 30
        $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 79 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...
82 30
        $headers = $this->buildHeaders($soapOperation);
83 30
        $this->requestMessage = $request = $this->messageFactory->createRequest('POST', $this->serviceDefinition['endpoint'], $headers, $xmlMessage);
84
85
        try {
86 30
            $this->responseMessage = $response = $this->client->sendRequest($request);
87 20
            if (strpos($response->getHeaderLine('Content-Type'), 'xml') === false) {
88 2
                throw new UnexpectedFormatException(
89 2
                    $response,
90 2
                    $request,
91 2
                    "Unexpected content type '" . $response->getHeaderLine('Content-Type') . "'"
92 2
                );
93
            }
94
95
            // fast return if no return is expected
96 18
            if (!count($soapOperation['output']['parts'])) {
97 4
                return null;
98
            }
99
100 14
            $body = (string)$response->getBody();
101
102 14
            $faultClass = $this->findFaultClass($response);
103
104 14
            if (strpos($body, ':Fault>') !== false) { // some server returns a fault with 200 OK HTTP
105 1
                $fault = $this->serializer->deserialize($body, $faultClass, 'xml');
106 1
                throw $fault->createException($response, $request);
107
            }
108
109 13
            $response = $this->serializer->deserialize($body, $soapOperation['output']['message_fqcn'], 'xml');
110 26
        } catch (HttpException $e) {
111 10
            if (strpos($e->getResponse()->getHeaderLine('Content-Type'), 'xml') !== false) {
112 6
                $faultClass = $this->findFaultClass($e->getResponse());
113 6
                $fault = $this->serializer->deserialize((string)$e->getResponse()->getBody(), $faultClass, 'xml');
114 6
                throw $fault->createException($e->getResponse(), $e->getRequest(), $e);
115
            } else {
116 4
                throw new ServerException(
117 4
                    $e->getResponse(),
118 4
                    $e->getRequest(),
119
                    $e
120 4
                );
121
            }
122
        }
123 13
        return $this->resultCreator->prepareResult($response, $soapOperation['output']);
124
    }
125
126
    /**
127
     * @return RequestInterface|null
128
     */
129
    public function __getLastRequestMessage()
130
    {
131
        return $this->requestMessage;
132
    }
133
134
    /**
135
     * @return ResponseInterface|null
136
     */
137
    public function __getLastResponseMessage()
138
    {
139
        return $this->responseMessage;
140
    }
141
142 20
    protected function findFaultClass(ResponseInterface $response)
143
    {
144 20
        if (strpos($response->getHeaderLine('Content-Type'), 'application/soap+xml') === 0) {
145 11
            return Fault12::class;
146
        } else {
147 9
            return Fault11::class;
148
        }
149
    }
150
151 30
    protected function buildHeaders(array $operation)
152
    {
153
        return [
154 30
            'Content-Type' => isset($operation['version']) && $operation['version'] === '1.2'
155 30
                ? 'application/soap+xml; charset=utf-8'
156 30
                : 'text/xml; charset=utf-8',
157 30
            'SoapAction' => '"' . $operation['action'] . '"',
158 30
        ];
159
    }
160
161 30
    protected function findOperation($functionName, array $serviceDefinition)
162
    {
163 30
        if (isset($serviceDefinition['operations'][$functionName])) {
164 29
            return $serviceDefinition['operations'][$functionName];
165
        }
166
167 1
        foreach ($serviceDefinition['operations'] as $operation) {
168 1
            if (strtolower($functionName) == strtolower($operation['method'])) {
169 1
                return $operation;
170
            }
171
        }
172
        throw new ClientException("Can not find an operation to run $functionName service call");
173
    }
174
}
175