Passed
Push — feature/issue-264 ( 16c0d2 )
by Mikaël
31:40 queued 28:41
created

Service::getMethodAnnotationBlock()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 1
dl 0
loc 12
ccs 8
cts 8
cp 1
crap 3
rs 10
c 0
b 0
f 0
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
        return null;
83
    }
84
85 46
    protected function fillClassProperties(PropertyContainer $properties): void
86
    {
87 46
    }
88
89
    protected function getPropertyAnnotationBlock(PhpProperty $property): ?PhpAnnotationBlock
90
    {
91
        return null;
92
    }
93
94 46
    protected function defineUseStatements(): AbstractModelFile
95
    {
96 46
        $this->getFile()->addUse(SoapFault::class);
97
98 46
        return parent::defineUseStatements();
99
    }
100
101 46
    protected function getClassDeclarationLineText(): string
102
    {
103 46
        return GeneratorOptions::VALUE_NONE === $this->getGenerator()->getOptionGatherMethods() ? 'This class stands for all operations' : parent::getClassDeclarationLineText();
104
    }
105
106 46
    protected function fillClassMethods(): void
107
    {
108
        $this
109 46
            ->addSoapHeaderMethods()
110 46
            ->addOperationsMethods()
111 46
            ->addGetResultMethod()
112
        ;
113 46
    }
114
115 46
    protected function addSoapHeaderMethods(): self
116
    {
117 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

117
        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...
118 46
            $this->addSoapHeaderFromMethod($method);
119
        }
120
121 46
        return $this;
122
    }
123
124 46
    protected function addSoapHeaderFromMethod(MethodModel $method): self
125
    {
126 46
        $soapHeaderNames = $method->getMetaValue(TagHeader::META_SOAP_HEADER_NAMES, []);
127 46
        $soapHeaderNamespaces = $method->getMetaValue(TagHeader::META_SOAP_HEADER_NAMESPACES, []);
128 46
        $soapHeaderTypes = $method->getMetaValue(TagHeader::META_SOAP_HEADER_TYPES, []);
129 46
        if (is_array($soapHeaderNames) && is_array($soapHeaderNamespaces) && is_array($soapHeaderTypes)) {
130 46
            foreach ($soapHeaderNames as $index => $soapHeaderName) {
131 12
                $methodName = $this->getSoapHeaderMethodName($soapHeaderName);
132 12
                if (is_null($this->methods->get($methodName))) {
133 12
                    $soapHeaderNamespace = array_key_exists($index, $soapHeaderNamespaces) ? $soapHeaderNamespaces[$index] : null;
134 12
                    $soapHeaderType = array_key_exists($index, $soapHeaderTypes) ? $soapHeaderTypes[$index] : null;
135 12
                    $this->methods->add($this->getSoapHeaderMethod($methodName, $soapHeaderName, $soapHeaderNamespace, $soapHeaderType));
0 ignored issues
show
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

135
                    $this->methods->add($this->getSoapHeaderMethod($methodName, $soapHeaderName, $soapHeaderNamespace, /** @scrutinizer ignore-type */ $soapHeaderType));
Loading history...
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

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