Passed
Push — develop ( 0a8b55...80d7ca )
by Mikaël
06:50
created

Service::getSoapHeaderMethod()   A

Complexity

Conditions 3
Paths 9

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3.0175

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 16
nc 9
nop 4
dl 0
loc 22
ccs 14
cts 16
cp 0.875
crap 3.0175
rs 9.7333
c 1
b 0
f 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace WsdlToPhp\PackageGenerator\File;
6
7
use InvalidArgumentException;
8
use SoapFault;
9
use WsdlToPhp\PackageGenerator\ConfigurationReader\GeneratorOptions;
10
use WsdlToPhp\PackageGenerator\Container\PhpElement\Constant as ConstantContainer;
11
use WsdlToPhp\PackageGenerator\Container\PhpElement\Property as PropertyContainer;
12
use WsdlToPhp\PackageGenerator\File\Element\PhpFunctionParameter;
13
use WsdlToPhp\PackageGenerator\File\Validation\Rules;
14
use WsdlToPhp\PackageGenerator\Generator\Generator;
15
use WsdlToPhp\PackageGenerator\Model\AbstractModel;
16
use WsdlToPhp\PackageGenerator\Model\Method as MethodModel;
17
use WsdlToPhp\PackageGenerator\Model\Service as ServiceModel;
18
use WsdlToPhp\PackageGenerator\Model\Struct as StructModel;
19
use WsdlToPhp\PackageGenerator\Model\StructAttribute as StructAttributeModel;
20
use WsdlToPhp\PackageGenerator\Parser\Wsdl\TagHeader;
21
use WsdlToPhp\PhpGenerator\Element\PhpAnnotation;
22
use WsdlToPhp\PhpGenerator\Element\PhpAnnotationBlock;
23
use WsdlToPhp\PhpGenerator\Element\PhpConstant;
24
use WsdlToPhp\PhpGenerator\Element\PhpFunctionParameter as PhpFunctionParameterBase;
25
use WsdlToPhp\PhpGenerator\Element\PhpMethod;
26
use WsdlToPhp\PhpGenerator\Element\PhpProperty;
27
28
final class Service extends AbstractModelFile
29
{
30
    public const METHOD_SET_HEADER_PREFIX = 'setSoapHeader';
31
    public const PARAM_SET_HEADER_NAMESPACE = 'namespace';
32
    public const PARAM_SET_HEADER_MUSTUNDERSTAND = 'mustUnderstand';
33
    public const PARAM_SET_HEADER_ACTOR = 'actor';
34
    public const METHOD_GET_RESULT = 'getResult';
35
36
    /**
37
     * Method model can't be found in case the original method's name is unclean:
38
     * - ex: my.operation.name becomes my_operation_name
39
     * thus the Model from Model\Service::getMethod() can't be found
40
     * So we store the generated name associated to the original method object.
41
     */
42
    protected array $methodNames = [];
43
44 48
    public static function getOperationMethodReturnType(MethodModel $method, Generator $generator): string
45
    {
46 48
        $returnType = $method->getReturnType();
47
48 48
        if (is_null($returnType)) {
49 2
            return 'null';
50
        }
51
52 46
        if ((($struct = $generator->getStructByName($returnType)) instanceof StructModel) && !$struct->isRestriction()) {
53 40
            if ($struct->isStruct()) {
54 40
                $returnType = $struct->getPackagedName(true);
55 8
            } elseif ($struct->isArray()) {
56 8
                if (($structInheritance = $struct->getInheritanceStruct()) instanceof StructModel) {
57 8
                    $returnType = sprintf('%s[]', $structInheritance->getPackagedName(true));
58
                } else {
59 4
                    $returnType = $struct->getInheritance();
60
                }
61
            }
62
        }
63
64 46
        return $returnType;
65
    }
66
67 50
    public function setModel(AbstractModel $model): self
68
    {
69 50
        if (!$model instanceof ServiceModel) {
70 2
            throw new InvalidArgumentException('Model must be an instance of a Service', __LINE__);
71
        }
72
73 48
        return parent::setModel($model);
0 ignored issues
show
Bug Best Practice introduced by
The expression return parent::setModel($model) returns the type WsdlToPhp\PackageGenerator\File\AbstractModelFile which includes types incompatible with the type-hinted return WsdlToPhp\PackageGenerator\File\Service.
Loading history...
74
    }
75
76 46
    protected function fillClassConstants(ConstantContainer $constants): void
77
    {
78 46
    }
79
80
    protected function getConstantAnnotationBlock(PhpConstant $constant): ?PhpAnnotationBlock
81
    {
82
    }
83
84 46
    protected function fillClassProperties(PropertyContainer $properties): void
85
    {
86 46
    }
87
88
    protected function getPropertyAnnotationBlock(PhpProperty $property): ?PhpAnnotationBlock
89
    {
90
    }
91
92 46
    protected function defineUseStatements(): AbstractModelFile
93
    {
94 46
        $this->getFile()->addUse(SoapFault::class);
95
96 46
        return parent::defineUseStatements();
97
    }
98
99 46
    protected function getClassDeclarationLineText(): string
100
    {
101 46
        return GeneratorOptions::VALUE_NONE === $this->getGenerator()->getOptionGatherMethods() ? 'This class stands for all operations' : parent::getClassDeclarationLineText();
102
    }
103
104 46
    protected function fillClassMethods(): void
105
    {
106
        $this
107 46
            ->addSoapHeaderMethods()
108 46
            ->addOperationsMethods()
109 46
            ->addGetResultMethod()
110
        ;
111 46
    }
112
113 46
    protected function addSoapHeaderMethods(): self
114
    {
115 46
        foreach ($this->getModel()->getMethods() as $method) {
0 ignored issues
show
Bug introduced by
The method getMethods() does not exist on WsdlToPhp\PackageGenerator\Model\AbstractModel. Did you maybe mean getMeta()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

115
        foreach ($this->getModel()->/** @scrutinizer ignore-call */ getMethods() as $method) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
116 46
            $this->addSoapHeaderFromMethod($method);
117
        }
118
119 46
        return $this;
120
    }
121
122 46
    protected function addSoapHeaderFromMethod(MethodModel $method): self
123
    {
124 46
        $soapHeaderNames = $method->getMetaValue(TagHeader::META_SOAP_HEADER_NAMES, []);
125 46
        $soapHeaderNamespaces = $method->getMetaValue(TagHeader::META_SOAP_HEADER_NAMESPACES, []);
126 46
        $soapHeaderTypes = $method->getMetaValue(TagHeader::META_SOAP_HEADER_TYPES, []);
127 46
        if (is_array($soapHeaderNames) && is_array($soapHeaderNamespaces) && is_array($soapHeaderTypes)) {
128 46
            foreach ($soapHeaderNames as $index => $soapHeaderName) {
129 12
                $methodName = $this->getSoapHeaderMethodName($soapHeaderName);
130 12
                if (is_null($this->methods->get($methodName))) {
131 12
                    $soapHeaderNamespace = array_key_exists($index, $soapHeaderNamespaces) ? $soapHeaderNamespaces[$index] : null;
132 12
                    $soapHeaderType = array_key_exists($index, $soapHeaderTypes) ? $soapHeaderTypes[$index] : null;
133 12
                    $this->methods->add($this->getSoapHeaderMethod($methodName, $soapHeaderName, $soapHeaderNamespace, $soapHeaderType));
0 ignored issues
show
Bug introduced by
It seems like $soapHeaderNamespace can also be of type null; however, parameter $soapHeaderNamespace of WsdlToPhp\PackageGenerat...::getSoapHeaderMethod() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

133
                    $this->methods->add($this->getSoapHeaderMethod($methodName, $soapHeaderName, /** @scrutinizer ignore-type */ $soapHeaderNamespace, $soapHeaderType));
Loading history...
Bug introduced by
It seems like $soapHeaderType can also be of type null; however, parameter $soapHeaderType of WsdlToPhp\PackageGenerat...::getSoapHeaderMethod() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

133
                    $this->methods->add($this->getSoapHeaderMethod($methodName, $soapHeaderName, $soapHeaderNamespace, /** @scrutinizer ignore-type */ $soapHeaderType));
Loading history...
134
                }
135
            }
136
        }
137
138 46
        return $this;
139
    }
140
141 12
    protected function getSoapHeaderMethod(string $methodName, string $soapHeaderName, string $soapHeaderNamespace, string $soapHeaderType): PhpMethod
142
    {
143
        try {
144 12
            $method = new PhpMethod($methodName, [
145 12
                $firstParameter = new PhpFunctionParameter(lcfirst($soapHeaderName), PhpFunctionParameterBase::NO_VALUE, $this->getTypeFromName($soapHeaderType)),
146 12
                new PhpFunctionParameterBase(self::PARAM_SET_HEADER_NAMESPACE, $soapHeaderNamespace, self::TYPE_STRING),
147 12
                new PhpFunctionParameterBase(self::PARAM_SET_HEADER_MUSTUNDERSTAND, false, self::TYPE_BOOL),
148 12
                new PhpFunctionParameterBase(self::PARAM_SET_HEADER_ACTOR, null, '?'.self::TYPE_STRING),
149 12
            ], self::TYPE_SELF);
150
151 12
            $model = $this->getModelByName($soapHeaderType);
152 12
            if ($model instanceof StructModel) {
153 12
                $rules = new Rules($this, $method, new StructAttributeModel($model->getGenerator(), $soapHeaderType, $model->getName(), $model), $this->methods);
154 12
                $rules->applyRules(lcfirst($soapHeaderName));
155 12
                $firstParameter->setModel($model);
156
            }
157 12
            $method->addChild(sprintf('return $this->%s($%s, \'%s\', $%s, $%s, $%s);', self::METHOD_SET_HEADER_PREFIX, self::PARAM_SET_HEADER_NAMESPACE, $soapHeaderName, lcfirst($soapHeaderName), self::PARAM_SET_HEADER_MUSTUNDERSTAND, self::PARAM_SET_HEADER_ACTOR));
158
        } catch (InvalidArgumentException $exception) {
159
            throw new InvalidArgumentException(sprintf('Unable to create function parameter for service "%s" with type "%s"', $this->getModel()->getName(), var_export($this->getTypeFromName($soapHeaderName), true)), __LINE__, $exception);
160
        }
161
162 12
        return $method;
163
    }
164
165 12
    protected function getTypeFromName(string $name): ?string
166
    {
167 12
        return self::getPhpType(
168 12
            $this->getStructAttributeTypeAsPhpType(new StructAttributeModel($this->generator, 'any', $name)),
169 12
            $this->getGenerator()->getOptionXsdTypesPath(),
170 12
            $this->getStructAttributeTypeAsPhpType(new StructAttributeModel($this->generator, 'any', $name))
171
        );
172
    }
173
174 12
    protected function getSoapHeaderMethodName(string $soapHeaderName): string
175
    {
176 12
        return sprintf('%s%s', self::METHOD_SET_HEADER_PREFIX, ucfirst($soapHeaderName));
177
    }
178
179 46
    protected function addOperationsMethods(): self
180
    {
181 46
        foreach ($this->getModel()->getMethods() as $method) {
182 46
            $this->addMainMethod($method);
183
        }
184
185 46
        return $this;
186
    }
187
188 46
    protected function addGetResultMethod(): self
189
    {
190 46
        $method = new PhpMethod(self::METHOD_GET_RESULT);
191 46
        $method->addChild('return parent::getResult();');
192 46
        $this->methods->add($method);
193
194 46
        return $this;
195
    }
196
197 46
    protected function addMainMethod(MethodModel $method): self
198
    {
199 46
        $methodFile = new Operation($method, $this->getGenerator());
200 46
        $mainMethod = $methodFile->getMainMethod();
201 46
        $this->methods->add($mainMethod);
202 46
        $this->setModelFromMethod($mainMethod, $method);
203
204 46
        return $this;
205
    }
206
207 46
    protected function getMethodAnnotationBlock(PhpMethod $method): PhpAnnotationBlock
208
    {
209 46
        $annotationBlock = new PhpAnnotationBlock();
210 46
        if (0 === mb_stripos($method->getName(), self::METHOD_SET_HEADER_PREFIX)) {
211 12
            $this->addAnnotationBlockForSoapHeaderMethod($annotationBlock, $method);
212 46
        } elseif (self::METHOD_GET_RESULT === $method->getName()) {
213 46
            $this->addAnnotationBlockForgetResultMethod($annotationBlock);
214
        } else {
215 46
            $this->addAnnotationBlockForOperationMethod($annotationBlock, $method);
216
        }
217
218 46
        return $annotationBlock;
219
    }
220
221 12
    protected function addAnnotationBlockForSoapHeaderMethod(PhpAnnotationBlock $annotationBlock, PhpMethod $method): self
222
    {
223 12
        $methodParameters = $method->getParameters();
224 12
        $firstParameter = array_shift($methodParameters);
225 12
        if ($firstParameter instanceof PhpFunctionParameter) {
226 12
            $annotationBlock->addChild(sprintf('Sets the %s SoapHeader param', ucfirst($firstParameter->getName())));
227 12
            $firstParameterType = $firstParameter->getType();
228 12
            if ($firstParameter->getModel() instanceof StructModel) {
229 12
                $firstParameterType = $this->getStructAttributeTypeAsPhpType(new StructAttributeModel($firstParameter->getModel()->getGenerator(), $firstParameter->getName(), $firstParameter->getModel()->getName(), $firstParameter->getModel()));
230 12
                if ($firstParameter->getModel()->isRestriction()) {
231
                    $annotationBlock
232 2
                        ->addChild(new PhpAnnotation(self::ANNOTATION_USES, sprintf('%s::%s()', $firstParameter->getModel()->getPackagedName(true), StructEnum::METHOD_VALUE_IS_VALID)))
233 2
                        ->addChild(new PhpAnnotation(self::ANNOTATION_USES, sprintf('%s::%s()', $firstParameter->getModel()->getPackagedName(true), StructEnum::METHOD_GET_VALID_VALUES)))
234 2
                        ->addChild(new PhpAnnotation(self::ANNOTATION_THROWS, InvalidArgumentException::class))
235
                    ;
236
                }
237
            }
238
            $annotationBlock
239 12
                ->addChild(new PhpAnnotation(self::ANNOTATION_USES, sprintf('%s::%s()', $this->getModel()->getExtends(true), self::METHOD_SET_HEADER_PREFIX)))
240 12
                ->addChild(new PhpAnnotation(self::ANNOTATION_PARAM, sprintf('%s $%s', $firstParameterType, $firstParameter->getName())))
241 12
                ->addChild(new PhpAnnotation(self::ANNOTATION_PARAM, sprintf('%s $%s', self::TYPE_STRING, self::PARAM_SET_HEADER_NAMESPACE)))
242 12
                ->addChild(new PhpAnnotation(self::ANNOTATION_PARAM, sprintf('%s $%s', self::TYPE_BOOL, self::PARAM_SET_HEADER_MUSTUNDERSTAND)))
243 12
                ->addChild(new PhpAnnotation(self::ANNOTATION_PARAM, sprintf('%s $%s', self::TYPE_STRING, self::PARAM_SET_HEADER_ACTOR)))
244 12
                ->addChild(new PhpAnnotation(self::ANNOTATION_RETURN, $this->getModel()->getPackagedName(true)))
245
            ;
246
        }
247
248 12
        return $this;
249
    }
250
251 46
    protected function addAnnotationBlockForOperationMethod(PhpAnnotationBlock $annotationBlock, PhpMethod $method): self
252
    {
253 46
        if (($model = $this->getModelFromMethod($method)) instanceof MethodModel) {
254 46
            $operationAnnotationBlock = new OperationAnnotationBlock($model, $this->getGenerator());
255 46
            $operationAnnotationBlock->addAnnotationBlockForOperationMethod($annotationBlock);
256
        }
257
258 46
        return $this;
259
    }
260
261 46
    protected function addAnnotationBlockForgetResultMethod(PhpAnnotationBlock $annotationBlock): self
262
    {
263
        $annotationBlock
264 46
            ->addChild('Returns the result')->addChild(new PhpAnnotation(self::ANNOTATION_SEE, sprintf('%s::getResult()', $this->getModel()->getExtends(true))))
265 46
            ->addChild(new PhpAnnotation(self::ANNOTATION_RETURN, $this->getServiceReturnTypes()))
266
        ;
267
268 46
        return $this;
269
    }
270
271 46
    protected function getServiceReturnTypes(): string
272
    {
273 46
        $returnTypes = [];
274 46
        foreach ($this->getModel()->getMethods() as $method) {
275 46
            $returnTypes[] = self::getOperationMethodReturnType($method, $this->getGenerator());
276
        }
277 46
        natcasesort($returnTypes);
278
279 46
        return implode('|', array_unique($returnTypes));
280
    }
281
282 46
    protected function getModelFromMethod(PhpMethod $method): ?MethodModel
283
    {
284 46
        $model = $this->getGenerator()->getServiceMethod($method->getName());
285 46
        if (!$model instanceof MethodModel) {
286 8
            $model = array_key_exists($method->getName(), $this->methodNames) ? $this->methodNames[$method->getName()] : null;
287
        }
288
289 46
        return $model;
290
    }
291
292 46
    protected function setModelFromMethod(PhpMethod $phpMethod, MethodModel $methodModel): self
293
    {
294 46
        $this->methodNames[$phpMethod->getName()] = $methodModel;
295
296 46
        return $this;
297
    }
298
}
299