GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — 3.x (#91)
by Jindřich
01:32
created

WebService::parseOutput()   C

Complexity

Conditions 9
Paths 7

Size

Total Lines 104

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 9.5338

Importance

Changes 0
Metric Value
cc 9
nc 7
nop 2
dl 0
loc 104
ccs 13
cts 16
cp 0.8125
crap 9.5338
rs 6.4444
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
declare(strict_types = 1);
3
4
namespace Skaut\Skautis\Wsdl;
5
6
use Skaut\Skautis\EventDispatcher\EventDispatcherTrait;
7
use Skaut\Skautis\InvalidArgumentException;
8
use Skaut\Skautis\SkautisQuery;
9
use SoapClient;
10
use SoapFault;
11
use stdClass;
12
13
/**
14
 * @author Hána František <[email protected]>
15
 */
16
class WebService implements WebServiceInterface
17
{
18
19
    use EventDispatcherTrait;
20
21
    public const EVENT_SUCCESS = 'success';
22
    public const EVENT_FAILURE = 'failure';
23
24
    /**
25
     * základní údaje volané při každém požadavku
26
     * ID_Application, ID_Login
27
     *
28
     * @var array<string, mixed>
29
     */
30
    protected $init;
31
32
    /**
33
     * @var SoapClient
34
     */
35
    protected $soapClient;
36
37
    /**
38
     * @param array<string, mixed> $soapOpts Nastaveni SOAP requestu
39
     * @throws InvalidArgumentException pokud je odkaz na WSDL soubor prázdný
40
     */
41 7
    public function __construct(SoapClient $soapClient, array $soapOpts)
42
    {
43 7
        $this->init = $soapOpts;
44 7
        $this->soapClient = $soapClient;
45 7
    }
46
47
    /**
48
     * @inheritdoc
49
     */
50 6
    public function call(string $functionName, array $arguments = [])
51
    {
52 6
        return $this->soapCall($functionName, $arguments);
53
    }
54
55
56
    /**
57
     * @inheritdoc
58
     */
59 5
    public function __call(string $functionName, array $arguments)
60
    {
61 5
        return $this->call($functionName, $arguments);
62
    }
63
64
    /**
65
     * Metoda provadejici SOAP pozadavek na servery Skautisu
66
     *
67
     * @see http://php.net/manual/en/soapclient.soapcall.php
68
     *
69
     * @param string $functionName Nazev akce k provedeni na WebService
70
     * @param array<int|string, mixed> $arguments ([0]=args [1]=cover)
71
     * @param array<string, mixed> $options Nastaveni
72
     * @param array<int, string> $inputHeaders Hlavicky pouzite pri odesilani
73
     * @param array<int, string> $outputHeaders Hlavicky ktere prijdou s odpovedi
74
     * @return array<int|string, mixed>|stdClass|null
0 ignored issues
show
Documentation introduced by
The doc-type array<int|string, could not be parsed: Expected ">" at position 7, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
75
     */
76 6
    protected function soapCall(
77
      string $functionName,
78
      array $arguments,
79
      array $options = [],
80
      array $inputHeaders = [],
81
      array &$outputHeaders = []
82
    ) {
83 6
        $fname = ucfirst($functionName);
84 6
        $args = $this->prepareArgs($fname, $arguments);
85
86 6
        if ($this->hasListeners()) {
87 2
            $query = new SkautisQuery($fname, $args, debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));
88
        }
89
90
        try {
91 6
            $soapResponse = $this->soapClient->__soapCall($fname, $args, $options, $inputHeaders, $outputHeaders);
92 4
$q = serialize($soapResponse);
0 ignored issues
show
Unused Code introduced by
$q is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
93 4
            $soapResponse = $this->parseOutput($fname, $soapResponse);
94
95 4
            if (isset($query) && $this->hasListeners()) {
96
                $this->dispatch(self::EVENT_SUCCESS, $query->done($soapResponse));
97
            }
98 4
            return $soapResponse;
99 2
        } catch (SoapFault $e) {
100 2
            if (isset($query) && $this->hasListeners()) {
101 2
              $this->dispatch(self::EVENT_FAILURE, $query->done(null, $e));
102
            }
103
104 2
            throw $this->convertToSkautisException($e);
105
        }
106
    }
107
108
    /**
109
     * Z defaultnich parametru a parametru callu vytvori argumenty pro SoapClient::__soapCall
110
     *
111
     * @param string $functionName Jmeno funkce volane pres SOAP
112
     * @param array<int|string, mixed> $arguments Argumenty k mergnuti s defaultnimy
113
     *
114
     * @return array<int, mixed> Argumenty pro SoapClient::__soapCall
0 ignored issues
show
Documentation introduced by
The doc-type array<int, could not be parsed: Expected ">" at position 5, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
115
     */
116 6
    protected function prepareArgs(string $functionName, array $arguments): array
117
    {
118 6
        if (!isset($arguments[0]) || !is_array($arguments[0])) {
119 2
            $arguments[0] = [];
120
        }
121
122
        //k argumentum připoji vlastni informace o aplikaci a uzivateli
123 6
        $args = array_merge($this->init, $arguments[0]);
124
125 6
        if (!isset($arguments[1])) {
126 6
            $functionName = lcfirst($functionName);
127 6
            $args = [[$functionName . 'Input' => $args]];
128 6
            return $args;
129
        }
130
131
        //pokud je zadan druhy parametr tak lze prejmenovat obal dat
132
        $matches = explode('/', $arguments[1]);
133
        //pole se budou vytvaret zevnitr ven
134
        $matches = array_reverse($matches);
135
136
        $matches[] = 0; //zakladni obal 0=>...
137
138
        foreach ($matches as $value) {
139
            $args = [$value => $args];
140
        }
141
142
        return $args;
143
    }
144
145
    /**
146
     * Parsuje output ze SoapClient do jednotného formátu
147
     *
148
     * @param string $fname Jméno funkce volané přes SOAP
149
     * @param mixed $ret    Odpoveď ze SoapClient::__soapCall
150
     *
151
     * @return array<int|string, mixed>|\stdClass|null
0 ignored issues
show
Documentation introduced by
The doc-type array<int|string, could not be parsed: Expected ">" at position 7, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
152
     */
153 4
    protected function parseOutput(string $fname, $ret)
154
    {
155
156
        /*
157
            Pokud se jedna o request ktery ma vracet jednu hodnotu a ta existuje, skautis vraci primo objekt odpovedi
158
                Napriklad:
159
                <UnitDetailResponse xmlns="https://is.skaut.cz/">
160
                    <UnitDetailResult>
161
                        data jednoho objektu
162
                    </UnitDetailResult>
163
                </UnitDetailResponse>
164
165
            To SoapClient naparsuje jako:
166
                class stdClass#25 (1) {
167
                    public $UnitDetailResult =>
168
                        class stdClass#26 (48) {
169
                            data objectu
170
                        }
171
                }
172
173
174
175
            Pokud se jedna o request ktery ma vracet jednu hodnotu a ta neexistuje, skautis vraci jeden self-closing tag
176
            Napriklad:
177
                <UnitDetailResponse xmlns="https://is.skaut.cz/" />
178
179
            To SoapClient naparsuje jako:
180
                class stdClass#25 (0) {
181
                }
182
183
            Pokud se jedna o request ktery ma vracet vice hodnot, vraci *Result/*Output
184
            Napriklad:
185
                <UnitAllResponse xmlns="https://is.skaut.cz/">
186
                    <UnitAllResult>
187
                        <UnitAllOutput>
188
                            data jednoho objektu
189
                        </UnitAllOutput>
190
                        <UnitAllOutput>
191
                            data dalsiho objektu
192
                        </UnitAllOutput>
193
                    </UnitAllResult>
194
                </UnitAllResponse>
195
196
            To SoapClient naparsuje jako:
197
                class stdClass#25 (1) {
198
                    public $UnitAllResult =>
199
                        class stdClass#26 (1) {
200
                            public $UnitAllOutput =>
201
                                array(2) {
202
                                    stdClass - data jednoho objektu,
203
                                    stdClass - data dalsiho objektu,
204
                                }
205
                        }
206
                    }
207
                }
208
209
            Pokud se jedna o request ktery ma vracet vice hodnot, vraci klasickou dvojici tagu
210
            Napriklad:
211
                <UnitAllResponse xmlns="https://is.skaut.cz/">
212
                    <UnitAllResult />
213
                </UnitAllResponse>
214
215
            To SoapClient naparsuje jako:
216
                class stdClass#25 (1) {
217
                    public $UnitAllResult =>
218
                        class stdClass#26 (0) {
219
                        }
220
                }
221
222
        */
223
224 4
        if (!$ret) {
225
            throw new \RuntimeException("unexpected output");
226
        }
227
228
        // Pokud byl vracen prazdny objekt predstavujici neexistujici vec
229 4
        if ($ret instanceof stdClass && count((array) $ret) === 0) {
230 1
            return null;
231
        }
232
233
        // Pokud obsahuje *Result pak se  bud jedna o existujici jeden objekt, vice objektu nebo prazdny seznam objektu
234 3
        $result = $ret->{$fname . 'Result'} ?? null;
235 3
        if (!isset($result)) {
236
            throw new \RuntimeException("unexpected output");
237
        }
238
239 3
        $output = $result->{$fname . 'Output'} ?? null;
240
        // Pokud obsahuje *Result, ale zadny *Output pak se jedna o jeden
241 3
        if (!isset($output)) {
242
            // Vraci prazdny object
243 2
            if ($result instanceof stdClass && count((array) $result) === 0) {
244 1
                return [];
245
            }
246
247 1
            return $result;
248
        }
249
250
        // Vraci pouze jednu hodnotu misto pole?
251 1
        if ($output instanceof stdClass) {
252
            return [$output];
253
        }
254
255 1
        return $output; //vraci pole se stdClass
256
    }
257
258 2
    private function convertToSkautisException(SoapFault $e): WsdlException
259
    {
260 2
      if (preg_match('/Uživatel byl odhlášen/ui', $e->getMessage())) {
261
        return new AuthenticationException($e->getMessage(), $e->getCode(), $e);
262
      }
263
264 2
      if (preg_match('/Nemáte oprávnění/ui', $e->getMessage())) {
265
        return new PermissionException($e->getMessage(), $e->getCode(), $e);
266
      }
267
268 2
      return new WsdlException($e->getMessage(), $e->getCode(), $e);
269
    }
270
}
271