ValidRule   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 5
dl 0
loc 46
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getSchema() 0 4 1
A doValidation() 0 32 5
1
<?php
2
3
namespace whm\Smoke\Rules\Xml\Rss;
4
5
use phm\HttpWebdriverClient\Http\Response\UriAwareResponse;
6
use Psr\Http\Message\ResponseInterface;
7
use whm\Smoke\Rules\CheckResult;
8
use whm\Smoke\Rules\StandardRule;
9
use whm\Smoke\Rules\ValidationFailedException;
10
11
/**
12
 * This rule checks if a rss feed is valid.
13
 */
14
class ValidRule extends StandardRule
15
{
16
    const SCHEMA = 'rss2_0.xsd';
17
18
    const PUBLIC_SERVICE = "https://validator.w3.org/feed/check.cgi?url=%s";
19
20
    protected $contentTypes = array('text/xml', 'application/xml', 'application/rss+xml');
21
22
    private function getSchema()
23
    {
24
        return __DIR__ . '/' . self::SCHEMA;
25
    }
26
27
    public function doValidation(ResponseInterface $response)
28
    {
29
        $body = (string)$response->getBody();
30
31
        if (preg_match('/<rss/', $body)) {
32
            libxml_clear_errors();
33
            $dom = new \DOMDocument();
34
            @$dom->loadXML($body);
35
            $lastError = libxml_get_last_error();
36
37
            if ($lastError) {
38
                throw new ValidationFailedException(
39
                    'The given xml file is not well formed (last error: ' .
40
                    str_replace("\n", '', $lastError->message) . ').');
41
            }
42
43
            $valid = @$dom->schemaValidate($this->getSchema());
44
45
            if (!$valid) {
46
                $lastError = libxml_get_last_error();
47
                $lastErrorMessage = str_replace("\n", '', $lastError->message);
48
49
                if ($response instanceof UriAwareResponse) {
50
                    $toolUrl = sprintf(self::PUBLIC_SERVICE, urlencode((string)$response->getUri()));
51
                } else {
52
                    $toolUrl = '';
53
                }
54
                return new CheckResult(CheckResult::STATUS_FAILURE, 'The given xml file is not a valid rss file (last error: ' . $lastErrorMessage . ').', null, $toolUrl);
55
            }
56
        }
57
        return new CheckResult(CheckResult::STATUS_SUCCESS, 'The given rss file is valid.');
58
    }
59
}
60