JsonSchemaRule::init()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace whm\Smoke\Rules\Json\JsonSchema;
4
5
use JsonSchema\Validator;
6
use Psr\Http\Message\ResponseInterface;
7
use whm\Smoke\Http\Response;
8
use whm\Smoke\Rules\StandardRule;
9
use whm\Smoke\Rules\ValidationFailedException;
10
11
/**
12
 * This rule checks if a JSON file is valid for a JSON schema file.
13
 */
14
class JsonSchemaRule extends StandardRule
15
{
16
    private $jsonSchemaFiles;
17
18
    protected $contentTypes = array('json');
19
20
    private $json_errors = array(
21
        JSON_ERROR_NONE => 'No Error',
22
        JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
23
        JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch',
24
        JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
25
        JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
26
        JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded',
27
    );
28
29
    public function init($jsonSchemaFiles)
30
    {
31
        $this->jsonSchemaFiles = $jsonSchemaFiles;
32
    }
33
34
    protected function doValidation(ResponseInterface $response)
35
    {
36
        $data = json_decode((string)$response->getBody());
37
        if ($data === null) {
38
            throw new ValidationFailedException("The given JSON data can not be validated (last error: '" . $this->json_errors[json_last_error()] . "').");
39
        } else {
40
            $errorStatus = false;
41
            $messageParts = array();
42
43
            foreach ($this->jsonSchemaFiles as $jsonSchemaFile) {
44
                $validator = new Validator();
45
46
                $jsonSchemaObject = (object) json_decode(file_get_contents($jsonSchemaFile['jsonfileurl']));
47
48
                $validator->check($data, $jsonSchemaObject);
49
50
                if (!$validator->isValid()) {
51
                    $errorStatus = true;
52
                    $errorMessage = '';
53
                    foreach ($validator->getErrors() as $error) {
54
                        $errorMessage = $errorMessage . sprintf("[%s] %s\n", $error['property'], $error['message']);
55
                    }
56
                    $messageParts[] = $jsonSchemaFile['jsonfilename'] . ' - ' . $jsonSchemaFile['jsonfileurl'] . '(last error: ' . $errorMessage . ').';
57
                }
58
            }
59
60 View Code Duplication
            if ($errorStatus === 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...
61
                $message = 'JSON file (' . (string) $response->getUri() . ')  does not validate against the following JSON Schema 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...
62
                throw new ValidationFailedException($message);
63
            }
64
        }
65
    }
66
}
67