Completed
Pull Request — master (#33)
by Robbert van den
02:22
created

Client::findOperation()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.25

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 6
cts 8
cp 0.75
rs 9.8333
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 4.25
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\SerializationContext;
21
use JMS\Serializer\Serializer;
22
use Psr\Http\Message\ResponseInterface;
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 32
    public function __construct(array $serviceDefinition, Serializer $serializer, MessageFactory $messageFactory, HttpClient $client, HeaderHandler $headerHandler)
56 1
    {
57 32
        $this->serviceDefinition = $serviceDefinition;
58 32
        $this->serializer = $serializer;
59
60 32
        $this->client = $client;
61 32
        $this->messageFactory = $messageFactory;
62 32
        $this->argumentsReader = new ArgumentsReader($this->serializer, $headerHandler);
63 32
        $this->resultCreator = new ResultCreator($this->serializer, !empty($serviceDefinition['unwrap']));
64 32
    }
65
66 30
    public function __call($functionName, array $args)
67
    {
68 30
        $soapOperation = $this->findOperation($functionName, $this->serviceDefinition);
69 30
        $message = $this->argumentsReader->readArguments($args, $soapOperation['input']);
70
71 30
        $xmlMessage = $this->serializer->serialize(
72 30
            $message,
0 ignored issues
show
Bug introduced by
It seems like $message defined by $this->argumentsReader->...soapOperation['input']) on line 69 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...
73 30
            'xml',
74 30
            (new SerializationContext())
75 30
                ->setAttribute('soapAction', $soapOperation['action'])
76 30
                ->setAttribute('soapEndpoint', $this->serviceDefinition['endpoint'])
77 30
        );
78
79 30
        $headers = $this->buildHeaders($soapOperation);
80 30
        $request = $this->messageFactory->createRequest('POST', $this->serviceDefinition['endpoint'], $headers, $xmlMessage);
81
82
        try {
83 30
            $response = $this->client->sendRequest($request);
84 20
            if (strpos($response->getHeaderLine('Content-Type'), 'xml') === false) {
85 2
                throw new UnexpectedFormatException(
86 2
                    $response,
87 2
                    $request,
88 2
                    "Unexpected content type '" . $response->getHeaderLine('Content-Type') . "'"
89 2
                );
90
            }
91
92
            // fast return if no return is expected
93 18
            if (!count($soapOperation['output']['parts'])) {
94 4
                return null;
95
            }
96
97 14
            $body = (string)$response->getBody();
98
99 14
            $faultClass = $this->findFaultClass($response);
100
101 14
            if (strpos($body, ':Fault>') !== false) { // some server returns a fault with 200 OK HTTP
102 1
                $fault = $this->serializer->deserialize($body, $faultClass, 'xml');
103 1
                throw $fault->createException($response, $request);
104
            }
105
106 13
            $response = $this->serializer->deserialize($body, $soapOperation['output']['message_fqcn'], 'xml');
107 26
        } catch (HttpException $e) {
108 10
            if (strpos($e->getResponse()->getHeaderLine('Content-Type'), 'xml') !== false) {
109 6
                $faultClass = $this->findFaultClass($e->getResponse());
110 6
                $fault = $this->serializer->deserialize((string)$e->getResponse()->getBody(), $faultClass, 'xml');
111 6
                throw $fault->createException($e->getResponse(), $e->getRequest(), $e);
112
            } else {
113 4
                throw new ServerException(
114 5
                    $e->getResponse(),
115 4
                    $e->getRequest(),
116
                    $e
117 4
                );
118
            }
119
        }
120 13
        return $this->resultCreator->prepareResult($response, $soapOperation['output']);
121
    }
122
123 20
    public function findFaultClass(ResponseInterface $response)
124
    {
125 20
        if (strpos($response->getHeaderLine('Content-Type'), 'application/soap+xml') === 0) {
126 11
            return Fault12::class;
127
        } else {
128 9
            return Fault11::class;
129
        }
130
    }
131
132 30
    protected function buildHeaders(array $operation)
133
    {
134
        return [
135 30
            'Content-Type' => isset($operation['version']) && $operation['version'] === '1.2'
136 30
                ? 'application/soap+xml; charset=utf-8'
137 30
                : 'text/xml; charset=utf-8',
138 30
            'SoapAction' => '"' . $operation['action'] . '"',
139 30
        ];
140
    }
141
142 30
    protected function findOperation($functionName, array $serviceDefinition)
143
    {
144 30
        if (isset($serviceDefinition['operations'][$functionName])) {
145 29
            return $serviceDefinition['operations'][$functionName];
146
        }
147
148 1
        foreach ($serviceDefinition['operations'] as $operation) {
149 1
            if (strtolower($functionName) == strtolower($operation['method'])) {
150 1
                return $operation;
151
            }
152
        }
153
        throw new ClientException("Can not find an operation to run $functionName service call");
154
    }
155
}
156