Completed
Push — master ( 2cf922...c5787e )
by Nils
01:47
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 Method

Rating   Name   Duplication   Size   Complexity  
B ValidRule::doValidation() 0 24 4
1
<?php
2
3
namespace whm\Smoke\Rules\Xml\Rss;
4
5
use Psr\Http\Message\ResponseInterface;
6
use whm\Smoke\Rules\Rule;
7
use whm\Smoke\Rules\StandardRule;
8
use whm\Smoke\Rules\ValidationFailedException;
9
10
/**
11
 * This rule checks if a rss feed is valid.
12
 */
13
class ValidRule extends StandardRule
14
{
15
    const SCHEMA = 'rss2_0.xsd';
16
17
    protected $contentTypes = array('text/xml', 'application/xml', 'application/rss+xml');
18
19
    private function getSchema()
20
    {
21
        return __DIR__ . '/' . self::SCHEMA;
22
    }
23
24
    public function doValidation(ResponseInterface $response)
25
    {
26
        $body = (string)$response->getBody();
27
        if (preg_match('/<rss/', $body)) {
28
            libxml_clear_errors();
29
            $dom = new \DOMDocument();
30
            @$dom->loadXML($body);
31
            $lastError = libxml_get_last_error();
32
            if ($lastError) {
33
                throw new ValidationFailedException(
34
                    'The given xml file is not well formed (last error: ' .
35
                    str_replace("\n", '', $lastError->message) . ').');
36
            }
37
            $valid = @$dom->schemaValidate($this->getSchema());
38
            if (!$valid) {
39
                $lastError = libxml_get_last_error();
40
                $lastErrorMessage = str_replace("\n", '', $lastError->message);
41
                throw new ValidationFailedException(
42
                    'The given xml file did not validate against ' .
43
                    $this->getSchema() . ' (last error: ' .
44
                    $lastErrorMessage . ').');
45
            }
46
        }
47
    }
48
}
49