Completed
Branch master (1f9106)
by Nils
02:44
created

ValidRule::validate()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 28
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 28
rs 8.439
cc 5
eloc 21
nc 5
nop 1
1
<?php
2
3
namespace whm\Smoke\Rules\Xml\Rss;
4
5
use whm\Smoke\Http\Response;
6
use whm\Smoke\Rules\Rule;
7
use whm\Smoke\Rules\ValidationFailedException;
8
9
/**
10
 * This rule checks if a rss feed is valid.
11
 */
12
class ValidRule implements Rule
13
{
14
    const SCHEMA = 'rss2_0.xsd';
15
16
    private function getSchema()
17
    {
18
        return __DIR__ . '/' . self::SCHEMA;
19
    }
20
21
    public function validate(Response $response)
22
    {
23
        if ($response->getContentType() !== 'text/xml') {
24
            return;
25
        }
26
27
        $body = $response->getBody();
28
        if (preg_match('/<rss/', $body)) {
29
            libxml_clear_errors();
30
            $dom = new \DOMDocument();
31
            @$dom->loadXML($body);
32
            $lastError = libxml_get_last_error();
33
            if ($lastError) {
34
                throw new ValidationFailedException(
35
                    'The given xml file is not well formed (last error: ' .
36
                    str_replace("\n", '', $lastError->message) . ').');
37
            }
38
            $valid = @$dom->schemaValidate($this->getSchema());
39
            if (!$valid) {
40
                $lastError = libxml_get_last_error();
41
                $lastErrorMessage = str_replace("\n", '', $lastError->message);
42
                throw new ValidationFailedException(
43
                    'The given xml file did not Validate vs. ' .
44
                    $this->getSchema() . ' (last error: ' .
45
                    $lastErrorMessage . ').');
46
            }
47
        }
48
    }
49
}
50