XmlValidXsdRule   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 9.52 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 4
loc 42
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 4 1
A doValidation() 4 26 4

How to fix   Duplicated Code   

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:

1
<?php
2
3
namespace whm\Smoke\Rules\Xml;
4
5
use Psr\Http\Message\ResponseInterface;
6
use whm\Smoke\Rules\StandardRule;
7
use whm\Smoke\Rules\ValidationFailedException;
8
9
/**
10
 * This rule checks if a sitemap.xml file is valid.
11
 */
12
class XmlValidXsdRule extends StandardRule
13
{
14
    private $xsdFiles;
15
16
    protected $contentTypes = array('text/xml', 'application/xml');
17
18
    public function init($xsdFiles)
19
    {
20
        $this->xsdFiles = $xsdFiles;
21
    }
22
23
    /**
24
     * @param ResponseInterface $response
25
     * @throws ValidationFailedException
26
     */
27
    protected function doValidation(ResponseInterface $response)
28
    {
29
        $body = (string)$response->getBody();
30
31
        $dom = new \DOMDocument();
32
        @$dom->loadXML($body);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
33
34
        $error = false;
35
        $messageParts = array();
36
37
        foreach ($this->xsdFiles as $xsdFile) {
38
            $valid = @$dom->schemaValidate($xsdFile['xsdfileurl']);
39
40
            if (!$valid) {
41
                $error = true;
42
                $lastError = libxml_get_last_error();
43
44
                $messageParts[] = $xsdFile['xsdfilename'] . ' - ' . $xsdFile['xsdfileurl'] . ' (last error: ' . str_replace("\n", '', $lastError->message) . ').';
45
            }
46
        }
47
48 View Code Duplication
        if ($error === true) {
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...
49
            $message = 'XML file (' . (string)$response->getUri() . ')  does not validate against the following XSD files: ' . implode(', ', $messageParts);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Http\Message\ResponseInterface as the method getUri() does only exist in the following implementations of said interface: phm\HttpWebdriverClient\...t\Chrome\ChromeResponse, phm\HttpWebdriverClient\...t\Guzzle\GuzzleResponse, phm\HttpWebdriverClient\...\Client\Guzzle\Response, phm\HttpWebdriverClient\...esponse\BrowserResponse, whm\Smoke\Http\ConnectionRefusedResponse, whm\Smoke\Http\ErrorResponse.

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...
50
            throw new ValidationFailedException($message);
51
        }
52
    }
53
}
54