PhpConverter   F
last analyzed

Complexity

Total Complexity 79

Size/Duplication

Total Lines 422
Duplicated Lines 27.01 %

Coupling/Cohesion

Components 1
Dependencies 19

Test Coverage

Coverage 90.64%

Importance

Changes 0
Metric Value
wmc 79
lcom 1
cbo 19
dl 114
loc 422
ccs 242
cts 267
cp 0.9064
rs 2.0547
c 0
b 0
f 0

19 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 20 1
A convert() 9 9 2
A getTypes() 0 14 3
B navigate() 20 20 6
A visitTypeBase() 0 14 4
A visitGroup() 11 11 3
A visitAttributeGroup() 8 11 3
B visitElementDef() 3 27 4
A isSkip() 0 4 1
B findPHPName() 3 30 4
C visitType() 21 40 12
A visitTypeAnonymous() 4 18 3
A visitComplexType() 12 12 3
D visitSimpleType() 0 29 9
A handleClassExtension() 0 14 2
B visitBaseComplexType() 8 20 5
A visitAttribute() 0 20 4
C visitElement() 10 41 7
A findPHPClass() 5 13 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like PhpConverter often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use PhpConverter, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace GoetasWebservices\Xsd\XsdToPhp\Php;
3
4
use Exception;
5
use GoetasWebservices\XML\XSDReader\Schema\Attribute\AttributeItem;
6
use GoetasWebservices\XML\XSDReader\Schema\Attribute\Group as AttributeGroup;
7
use GoetasWebservices\XML\XSDReader\Schema\Element\Element;
8
use GoetasWebservices\XML\XSDReader\Schema\Element\ElementDef;
9
use GoetasWebservices\XML\XSDReader\Schema\Element\ElementRef;
10
use GoetasWebservices\XML\XSDReader\Schema\Element\ElementSingle;
11
use GoetasWebservices\XML\XSDReader\Schema\Element\Group;
12
use GoetasWebservices\XML\XSDReader\Schema\Item;
13
use GoetasWebservices\XML\XSDReader\Schema\Schema;
14
use GoetasWebservices\XML\XSDReader\Schema\Type\BaseComplexType;
15
use GoetasWebservices\XML\XSDReader\Schema\Type\ComplexType;
16
use GoetasWebservices\XML\XSDReader\Schema\Type\SimpleType;
17
use GoetasWebservices\XML\XSDReader\Schema\Type\Type;
18
use GoetasWebservices\Xsd\XsdToPhp\AbstractConverter;
19
use GoetasWebservices\Xsd\XsdToPhp\Naming\NamingStrategy;
20
use GoetasWebservices\Xsd\XsdToPhp\Php\Structure\PHPArg;
21
use GoetasWebservices\Xsd\XsdToPhp\Php\Structure\PHPClass;
22
use GoetasWebservices\Xsd\XsdToPhp\Php\Structure\PHPClassOf;
23
use GoetasWebservices\Xsd\XsdToPhp\Php\Structure\PHPProperty;
24
use Psr\Log\LoggerInterface;
25
26
class PhpConverter extends AbstractConverter
27
{
28
29 31
    public function __construct(NamingStrategy $namingStrategy, LoggerInterface $loggerInterface = null)
30
    {
31 31
        parent::__construct($namingStrategy, $loggerInterface);
32
33
        $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "dateTime", function (Type $type) {
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
34 3
            return "DateTime";
35 31
        });
36
        $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "time", function (Type $type) {
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
37
            return "DateTime";
38 31
        });
39
        $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "date", function (Type $type) {
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
40
            return "DateTime";
41 31
        });
42
        $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "anySimpleType", function (Type $type) {
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
43
            return "mixed";
44 31
        });
45
        $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "anyType", function (Type $type) {
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
46 2
            return "mixed";
47 31
        });
48 31
    }
49
50
    private $classes = [];
51
52 31 View Code Duplication
    public function convert(array $schemas)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
53
    {
54 31
        $visited = array();
55 31
        $this->classes = array();
56 31
        foreach ($schemas as $schema) {
57 31
            $this->navigate($schema, $visited);
58 31
        }
59 31
        return $this->getTypes();
60
    }
61
62
    /**
63
     *
64
     * @return PHPClass[]
65
     */
66
    private function getTypes()
67
    {
68 31
        uasort($this->classes, function ($a, $b) {
69 20
            return strcmp($a["class"]->getFullName(), $b["class"]->getFullName());
70 31
        });
71 31
        $ret = array();
72 31
        foreach ($this->classes as $classData) {
73 30
            if (empty($classData["skip"])) {
74 30
                $ret[$classData["class"]->getFullName()] = $classData["class"];
75 30
            }
76 31
        }
77
78 31
        return $ret;
79
    }
80
81 31 View Code Duplication
    private function navigate(Schema $schema, array &$visited)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
82
    {
83 31
        if (isset($visited[spl_object_hash($schema)])) {
84
            return;
85
        }
86 31
        $visited[spl_object_hash($schema)] = true;
87
88 31
        foreach ($schema->getTypes() as $type) {
89 17
            $this->visitType($type);
90 31
        }
91 31
        foreach ($schema->getElements() as $element) {
92 15
            $this->visitElementDef($element);
93 31
        }
94
95 31
        foreach ($schema->getSchemas() as $schildSchema) {
96 31
            if (!in_array($schildSchema->getTargetNamespace(), $this->baseSchemas, true)) {
97 1
                $this->navigate($schildSchema, $visited);
98 1
            }
99 31
        }
100 31
    }
101
102 25
    private function visitTypeBase(PHPClass $class, Type $type)
103
    {
104 25
        $class->setAbstract($type->isAbstract());
105
106 25
        if ($type instanceof SimpleType) {
107 9
            $this->visitSimpleType($class, $type);
108 9
        }
109 25
        if ($type instanceof BaseComplexType) {
110 20
            $this->visitBaseComplexType($class, $type);
111 20
        }
112 25
        if ($type instanceof ComplexType) {
113 18
            $this->visitComplexType($class, $type);
114 18
        }
115 25
    }
116
117 3 View Code Duplication
    private function visitGroup(PHPClass $class, Schema $schema, Group $group)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
118
    {
119 3
        foreach ($group->getElements() as $childGroup) {
120 3
            if ($childGroup instanceof Group) {
121 1
                $this->visitGroup($class, $schema, $childGroup);
122 1
            } else {
123 3
                $property = $this->visitElement($class, $schema, $childGroup);
124 3
                $class->addProperty($property);
125
            }
126 3
        }
127 3
    }
128
129 1
    private function visitAttributeGroup(PHPClass $class, Schema $schema, AttributeGroup $att)
130
    {
131 1 View Code Duplication
        foreach ($att->getAttributes() as $childAttr) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
132 1
            if ($childAttr instanceof AttributeGroup) {
133 1
                $this->visitAttributeGroup($class, $schema, $childAttr);
134 1
            } else {
135 1
                $property = $this->visitAttribute($class, $schema, $childAttr);
136 1
                $class->addProperty($property);
137
            }
138 1
        }
139 1
    }
140
141
    private $skipByType = [];
142
143
    /**
144
     * @param ElementDef $element
145
     * @param bool $skip
146
     * @return PHPClass
147
     */
148 15
    public function visitElementDef(ElementDef $element, $skip = false)
149
    {
150 15
        if (!isset($this->classes[spl_object_hash($element)])) {
151 15
            $schema = $element->getSchema();
152
153 15
            $class = new PHPClass();
154 15
            $class->setDoc($element->getDoc());
155 15
            $class->setName($this->getNamingStrategy()->getItemName($element));
156 15
            $class->setDoc($element->getDoc());
157
158 15 View Code Duplication
            if (!isset($this->namespaces[$schema->getTargetNamespace()])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
159
                throw new Exception(sprintf("Can't find a PHP namespace to '%s' namespace", $schema->getTargetNamespace()));
160
            }
161 15
            $class->setNamespace($this->namespaces[$schema->getTargetNamespace()]);
162
163 15
            $this->classes[spl_object_hash($element)]["class"] = $class;
164 15
            $this->classes[spl_object_hash($element)]["skip"] = $skip;
165 15
            $this->skipByType[spl_object_hash($class)] = $skip;
166
167 15
            if (!$element->getType()->getName()) {
168 8
                $this->visitTypeBase($class, $element->getType());
169 8
            } else {
170 8
                $this->handleClassExtension($class, $element->getType());
171
            }
172 15
        }
173 15
        return $this->classes[spl_object_hash($element)]["class"];
174
    }
175
176
    public function isSkip($class)
177
    {
178
        return !empty($this->skipByType[spl_object_hash($class)]);
179
    }
180
181 17
    private function findPHPName(Type $type)
182
    {
183 17
        $schema = $type->getSchema();
184
185 17
        if ($className = $this->getTypeAlias($type)) {
186
187
            if (($pos = strrpos($className, '\\')) !== false) {
188
                return [
189
                    substr($className, $pos + 1),
190
                    substr($className, 0, $pos)
191
                ];
192
            } else {
193
                return [
194
                    $className,
195
                    null
196
                ];
197
            }
198
        }
199
200 17
        $name = $this->getNamingStrategy()->getTypeName($type);
201
202 17 View Code Duplication
        if (!isset($this->namespaces[$schema->getTargetNamespace()])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
203
            throw new Exception(sprintf("Can't find a PHP namespace to '%s' namespace", $schema->getTargetNamespace()));
204
        }
205 17
        $ns = $this->namespaces[$schema->getTargetNamespace()];
206
        return [
207 17
            $name,
208
            $ns
209 17
        ];
210
    }
211
212
    /**
213
     *
214
     * @param Type $type
215
     * @param boolean $force
216
     * @return \GoetasWebservices\Xsd\XsdToPhp\Php\Structure\PHPClass
217
     */
218 19
    public function visitType(Type $type, $force = false, $skip = false)
219
    {
220 19
        if (!isset($this->classes[spl_object_hash($type)])) {
221
222 19
            $this->classes[spl_object_hash($type)]["class"] = $class = new PHPClass();
223
224 19 View Code Duplication
            if ($alias = $this->getTypeAlias($type)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
225 18
                $class->setName($alias);
226 18
                $this->classes[spl_object_hash($type)]["skip"] = true;
227 18
                $this->skipByType[spl_object_hash($class)] = true;
228 18
                return $class;
229
            }
230
231 17
            list ($name, $ns) = $this->findPHPName($type);
232 17
            $class->setName($name);
233 17
            $class->setNamespace($ns);
234
235 17
            $class->setDoc($type->getDoc() . PHP_EOL . "XSD Type: " . ($type->getName() ?: 'anonymous'));
236
237 17
            $this->visitTypeBase($class, $type);
238
239 17 View Code Duplication
            if ($type instanceof SimpleType) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
240 3
                $this->classes[spl_object_hash($type)]["skip"] = true;
241 3
                $this->skipByType[spl_object_hash($class)] = true;
242 3
                return $class;
243
            }
244 17 View Code Duplication
            if (($this->isArrayType($type) || $this->isArrayNestedElement($type)) && !$force) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
245 4
                $this->classes[spl_object_hash($type)]["skip"] = true;
246 4
                $this->skipByType[spl_object_hash($class)] = true;
247 4
                return $class;
248
            }
249
250 17
            $this->classes[spl_object_hash($type)]["skip"] = $skip || !!$this->getTypeAlias($type);
251 17 View Code Duplication
        } elseif ($force) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
252 8
            if (!($type instanceof SimpleType) && !$this->getTypeAlias($type)) {
253 3
                $this->classes[spl_object_hash($type)]["skip"] = false;
254 3
            }
255 8
        }
256 17
        return $this->classes[spl_object_hash($type)]["class"];
257
    }
258
259
    /**
260
     * @param Type $type
261
     * @param string $name
262
     * @param PHPClass $parentClass
263
     * @return \GoetasWebservices\Xsd\XsdToPhp\Php\Structure\PHPClass
264
     */
265 3
    private function visitTypeAnonymous(Type $type, $name, PHPClass $parentClass)
266
    {
267 3
        if (!isset($this->classes[spl_object_hash($type)])) {
268 3
            $this->classes[spl_object_hash($type)]["class"] = $class = new PHPClass();
269 3
            $class->setName($this->getNamingStrategy()->getAnonymousTypeName($type, $name));
270
271 3
            $class->setNamespace($parentClass->getNamespace() . "\\" . $parentClass->getName());
272 3
            $class->setDoc($type->getDoc());
273
274 3
            $this->visitTypeBase($class, $type);
275
276 3 View Code Duplication
            if ($type instanceof SimpleType) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
277 2
                $this->classes[spl_object_hash($type)]["skip"] = true;
278 2
                $this->skipByType[spl_object_hash($class)] = true;
279 2
            }
280 3
        }
281 3
        return $this->classes[spl_object_hash($type)]["class"];
282
    }
283
284 18 View Code Duplication
    private function visitComplexType(PHPClass $class, ComplexType $type)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
285
    {
286 18
        $schema = $type->getSchema();
287 18
        foreach ($type->getElements() as $element) {
288 18
            if ($element instanceof Group) {
289 3
                $this->visitGroup($class, $schema, $element);
290 3
            } else {
291 17
                $property = $this->visitElement($class, $schema, $element);
292 17
                $class->addProperty($property);
293
            }
294 18
        }
295 18
    }
296
297 9
    private function visitSimpleType(PHPClass $class, SimpleType $type)
298
    {
299 9
        if ($restriction = $type->getRestriction()) {
300 8
            $parent = $restriction->getBase();
301
302 8
            if ($parent instanceof Type) {
303 8
                $this->handleClassExtension($class, $parent);
304 8
            }
305
306 8
            foreach ($restriction->getChecks() as $typeCheck => $checks) {
307 1
                foreach ($checks as $check) {
308 1
                    $class->addCheck('__value', $typeCheck, $check);
309 1
                }
310 8
            }
311 9
        } elseif ($unions = $type->getUnions()) {
312 1
            $types = array();
313 1
            foreach ($unions as $i => $unon) {
314 1
                if (!$unon->getName()) {
315 1
                    $types[] = $this->visitTypeAnonymous($unon, $type->getName() . $i, $class);
316 1
                } else {
317 1
                    $types[] = $this->visitType($unon);
318
                }
319 1
            }
320
321 1
            if ($candidato = reset($types)) {
322 1
                $class->setExtends($candidato);
323 1
            }
324 1
        }
325 9
    }
326
327 17
    private function handleClassExtension(PHPClass $class, Type $type)
328
    {
329
330 17
        if ($alias = $this->getTypeAlias($type)) {
331 16
            $c = PHPClass::createFromFQCN($alias);
332 16
            $val = new PHPProperty('__value');
333 16
            $val->setType($c);
334 16
            $c->addProperty($val);
335 16
            $class->setExtends($c);
336 16
        } else {
337 2
            $extension = $this->visitType($type, true);
338 2
            $class->setExtends($extension);
339
        }
340 17
    }
341
342 20
    private function visitBaseComplexType(PHPClass $class, BaseComplexType $type)
343
    {
344 20
        $parent = $type->getParent();
345 20
        if ($parent) {
346 4
            $parentType = $parent->getBase();
347 4
            if ($parentType instanceof Type) {
348 4
                $this->handleClassExtension($class, $parentType);
349 4
            }
350 4
        }
351 20
        $schema = $type->getSchema();
352
353 20 View Code Duplication
        foreach ($type->getAttributes() as $attr) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
354 7
            if ($attr instanceof AttributeGroup) {
355 1
                $this->visitAttributeGroup($class, $schema, $attr);
356 1
            } else {
357 7
                $property = $this->visitAttribute($class, $schema, $attr);
358 7
                $class->addProperty($property);
359
            }
360 20
        }
361 20
    }
362
363 7
    private function visitAttribute(PHPClass $class, Schema $schema, AttributeItem $attribute, $arrayize = true)
0 ignored issues
show
Unused Code introduced by
The parameter $schema is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
364
    {
365 7
        $property = new PHPProperty();
366 7
        $property->setName($this->getNamingStrategy()->getPropertyName($attribute));
367
368 7
        if ($arrayize && $itemOfArray = $this->isArrayType($attribute->getType())) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface GoetasWebservices\XML\XS...Attribute\AttributeItem as the method getType() does only exist in the following implementations of said interface: GoetasWebservices\XML\XS...ema\Attribute\Attribute, GoetasWebservices\XML\XS...\Attribute\AttributeDef, GoetasWebservices\XML\XS...\Attribute\AttributeRef.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
369
            if ($attribute->getType()->getName()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface GoetasWebservices\XML\XS...Attribute\AttributeItem as the method getType() does only exist in the following implementations of said interface: GoetasWebservices\XML\XS...ema\Attribute\Attribute, GoetasWebservices\XML\XS...\Attribute\AttributeDef, GoetasWebservices\XML\XS...\Attribute\AttributeRef.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
370
                $arg = new PHPArg($this->getNamingStrategy()->getPropertyName($attribute));
371
                $arg->setType($this->visitType($itemOfArray));
372
                $property->setType(new PHPClassOf($arg));
373
            } else {
374
                $property->setType($this->visitTypeAnonymous($attribute->getType(), $attribute->getName(), $class));
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface GoetasWebservices\XML\XS...Attribute\AttributeItem as the method getType() does only exist in the following implementations of said interface: GoetasWebservices\XML\XS...ema\Attribute\Attribute, GoetasWebservices\XML\XS...\Attribute\AttributeDef, GoetasWebservices\XML\XS...\Attribute\AttributeRef.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
375
            }
376
        } else {
377 7
            $property->setType($this->findPHPClass($class, $attribute, true));
0 ignored issues
show
Documentation introduced by
$attribute is of type object<GoetasWebservices...ttribute\AttributeItem>, but the function expects a object<GoetasWebservices...\XSDReader\Schema\Item>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
378
        }
379
380 7
        $property->setDoc($attribute->getDoc());
381 7
        return $property;
382
    }
383
384
    /**
385
     *
386
     * @param PHPClass $class
387
     * @param Schema $schema
388
     * @param Element $element
389
     * @param boolean $arrayize
390
     * @return \GoetasWebservices\Xsd\XsdToPhp\Structure\PHPProperty
391
     */
392 18
    private function visitElement(PHPClass $class, Schema $schema, ElementSingle $element, $arrayize = true)
393
    {
394 18
        $property = new PHPProperty();
395 18
        $property->setName($this->getNamingStrategy()->getPropertyName($element));
396 18
        $property->setDoc($element->getDoc());
397
398 18
        $t = $element->getType();
399
400 18
        if ($arrayize) {
401 18
            if ($itemOfArray = $this->isArrayType($t)) {
402 1 View Code Duplication
                if (!$itemOfArray->getName()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
403
                    $classType = $this->visitTypeAnonymous($itemOfArray, $element->getName(), $class);
404
                } else {
405 1
                    $classType = $this->visitType($itemOfArray);
406
                }
407
408 1
                $arg = new PHPArg($this->getNamingStrategy()->getPropertyName($element));
409 1
                $arg->setType($classType);
410 1
                $property->setType(new PHPClassOf($arg));
411 1
                return $property;
412 17
            } elseif ($itemOfArray = $this->isArrayNestedElement($t)) {
413 4 View Code Duplication
                if (!$t->getName()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
414
                    $classType = $this->visitTypeAnonymous($t, $element->getName(), $class);
415
                } else {
416 4
                    $classType = $this->visitType($t);
417
                }
418 4
                $elementProp = $this->visitElement($classType, $schema, $itemOfArray, false);
419 4
                $property->setType(new PHPClassOf($elementProp));
420 4
                return $property;
421 17
            } elseif ($this->isArrayElement($element)) {
422 8
                $arg = new PHPArg($this->getNamingStrategy()->getPropertyName($element));
423 8
                $arg->setType($this->findPHPClass($class, $element));
0 ignored issues
show
Documentation introduced by
$element is of type object<GoetasWebservices...\Element\ElementSingle>, but the function expects a object<GoetasWebservices...\XSDReader\Schema\Item>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
424 8
                $arg->setDefault('array()');
425 8
                $property->setType(new PHPClassOf($arg));
426 8
                return $property;
427
            }
428 12
        }
429
430 16
        $property->setType($this->findPHPClass($class, $element, true));
0 ignored issues
show
Documentation introduced by
$element is of type object<GoetasWebservices...\Element\ElementSingle>, but the function expects a object<GoetasWebservices...\XSDReader\Schema\Item>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
431 16
        return $property;
432
    }
433
434 18
    private function findPHPClass(PHPClass $class, Item $node, $force = false)
435
    {
436
437 18
        if ($node instanceof ElementRef) {
438 5
            return $this->visitElementDef($node->getReferencedElement());
439
        }
440
441 17 View Code Duplication
        if (!$node->getType()->getName()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
442 3
            return $this->visitTypeAnonymous($node->getType(), $node->getName(), $class);
443
        } else {
444 17
            return $this->visitType($node->getType(), $force);
445
        }
446
    }
447
}
448