1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace DL\SitemapBundle\Service; |
5
|
|
|
|
6
|
|
|
use DL\SitemapBundle\Definition\SitemapResource; |
7
|
|
|
use DL\SitemapBundle\Enum\ChangeFrequencyEnum; |
8
|
|
|
use DL\SitemapBundle\Exception\SitemapException; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Handles the validation of sitemap resources. |
12
|
|
|
* |
13
|
|
|
* @package DL\SitemapBundle\Service |
14
|
|
|
* @author Petre Pătrașc <[email protected]> |
15
|
|
|
*/ |
16
|
|
|
class SitemapResourceValidator |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* Validate a sitemap resource. |
20
|
|
|
* |
21
|
|
|
* @param SitemapResource $resource |
22
|
|
|
* |
23
|
|
|
* @return bool |
24
|
|
|
* @throws SitemapException |
25
|
|
|
*/ |
26
|
10 |
|
public function validate(SitemapResource $resource): bool |
27
|
|
|
{ |
28
|
10 |
|
if ('' === trim($resource->getTitle())) { |
29
|
1 |
|
throw new SitemapException('No title provided for the sitemap resource'); |
30
|
|
|
} |
31
|
|
|
|
32
|
9 |
|
if ('' === trim($resource->getLocation())) { |
33
|
1 |
|
throw new SitemapException('No location provided for the sitemap resource'); |
34
|
|
|
} |
35
|
|
|
|
36
|
8 |
|
if ('' === trim($resource->getChangeFrequency())) { |
37
|
1 |
|
throw new SitemapException('No change frequency provided for the sitemap resource'); |
38
|
|
|
} |
39
|
|
|
|
40
|
7 |
|
if (-1 == $resource->getPriority()) { |
41
|
1 |
|
throw new SitemapException('No priority provided for the sitemap resource'); |
42
|
|
|
} |
43
|
|
|
|
44
|
6 |
|
if ($resource->getPriority() < 0.0 || $resource->getPriority() > 1.0) { |
45
|
2 |
|
throw new SitemapException("Sitemap resource priority should be between 0.0 and 1.0." . |
46
|
2 |
|
" {$resource->getPriority()} provided."); |
47
|
|
|
} |
48
|
|
|
|
49
|
4 |
|
if (false === in_array($resource->getChangeFrequency(), $this->getValidChangeFrequencies())) { |
50
|
1 |
|
throw new SitemapException("Invalid sitemap change frequency provided: {$resource->getChangeFrequency()}"); |
51
|
|
|
} |
52
|
|
|
|
53
|
3 |
|
if (false === filter_var($resource->getLocation(), FILTER_VALIDATE_URL)) { |
54
|
2 |
|
throw new SitemapException("Invalid absolute location: {$resource->getLocation()}"); |
55
|
|
|
} |
56
|
|
|
|
57
|
1 |
|
return true; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Retrieve a list of the valid change frequencies. |
62
|
|
|
* |
63
|
|
|
* @return array |
64
|
|
|
*/ |
65
|
4 |
|
private function getValidChangeFrequencies(): array |
66
|
|
|
{ |
67
|
|
|
return [ |
68
|
4 |
|
ChangeFrequencyEnum::ALWAYS, |
69
|
|
|
ChangeFrequencyEnum::HOURLY, |
70
|
|
|
ChangeFrequencyEnum::DAILY, |
71
|
|
|
ChangeFrequencyEnum::WEEKLY, |
72
|
|
|
ChangeFrequencyEnum::MONTHLY, |
73
|
|
|
ChangeFrequencyEnum::YEARLY, |
74
|
|
|
ChangeFrequencyEnum::NEVER, |
75
|
|
|
]; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|