1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace whm\Smoke\Rules\Xml\Sitemap; |
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 SITEINDEX = 'siteindex.xsd'; |
15
|
|
|
const SITEMAP = 'sitemap.xsd'; |
16
|
|
|
|
17
|
|
|
private function getSchema($name = 'index') |
18
|
|
|
{ |
19
|
|
|
switch ($name) { |
20
|
|
|
case 'map': |
21
|
|
|
return __DIR__ . '/' . self::SITEMAP; |
22
|
|
|
case 'index': |
23
|
|
|
default: |
24
|
|
|
return __DIR__ . '/' . self::SITEINDEX; |
25
|
|
|
} |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function validate(Response $response) |
29
|
|
|
{ |
30
|
|
|
if ($response->getContentType() !== 'text/xml') { |
31
|
|
|
return; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
$body = $response->getBody(); |
35
|
|
|
|
36
|
|
|
if (0 === preg_match('/<(sitemapindex|urlset)/', $body)) { |
37
|
|
|
return; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
libxml_clear_errors(); |
41
|
|
|
$dom = new \DOMDocument(); |
42
|
|
|
@$dom->loadXML($body); |
|
|
|
|
43
|
|
|
$lastError = libxml_get_last_error(); |
44
|
|
|
if ($lastError) { |
45
|
|
|
throw new ValidationFailedException( |
46
|
|
|
'The given sitemap file is not well formed (last error: ' . |
47
|
|
|
str_replace("\n", '', $lastError->message) . ').'); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
if (preg_match('/<sitemapindex/', $body)) { |
51
|
|
|
$valid = @$dom->schemaValidate($this->getSchema('index')); |
52
|
|
|
} elseif (preg_match('/<urlset/', $body)) { |
53
|
|
|
$valid = @$dom->schemaValidate($this->getSchema('map')); |
54
|
|
|
} else { |
55
|
|
|
$valid = false; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
View Code Duplication |
if (!$valid) { |
|
|
|
|
59
|
|
|
$lastError = libxml_get_last_error(); |
60
|
|
|
$lastErrorMessage = str_replace("\n", '', $lastError->message); |
61
|
|
|
throw new ValidationFailedException( |
62
|
|
|
'The given sitemap file did not validate vs. ' . |
63
|
|
|
$this->getSchema() . ' (last error: ' . |
64
|
|
|
$lastErrorMessage . ').'); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
If you suppress an error, we recommend checking for the error condition explicitly: