1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Sitemap; |
4
|
|
|
|
5
|
|
|
use Spatie\Crawler\Crawler; |
6
|
|
|
use Spatie\Crawler\Url as CrawlerUrl; |
7
|
|
|
use Spatie\Sitemap\Crawler\Observer; |
8
|
|
|
use Spatie\Sitemap\Crawler\Profile; |
9
|
|
|
use Spatie\Sitemap\Tags\Url; |
10
|
|
|
|
11
|
|
|
class SitemapGenerator |
12
|
|
|
{ |
13
|
|
|
/** @var string */ |
14
|
|
|
protected $url = ''; |
15
|
|
|
|
16
|
|
|
/** @var \Spatie\Crawler\Crawler */ |
17
|
|
|
protected $crawler; |
18
|
|
|
|
19
|
|
|
/** @var callable */ |
20
|
|
|
protected $hasCrawled; |
21
|
|
|
|
22
|
|
|
/** @var callable */ |
23
|
|
|
protected $crawlProfile; |
24
|
|
|
|
25
|
|
|
/** @var \Spatie\Sitemap\Sitemap */ |
26
|
|
|
protected $sitemap; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param string $url |
30
|
|
|
* |
31
|
|
|
* @return static |
32
|
|
|
*/ |
33
|
|
|
public static function create(string $url) |
34
|
|
|
{ |
35
|
|
|
return app(self::class)->setUrl($url); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function __construct(Crawler $crawler) |
39
|
|
|
{ |
40
|
|
|
$this->crawler = $crawler; |
41
|
|
|
|
42
|
|
|
$this->sitemap = new Sitemap(); |
43
|
|
|
|
44
|
|
|
$this->hasCrawled = function (Url $url) { |
45
|
|
|
return $url; |
46
|
|
|
}; |
47
|
|
|
|
48
|
|
|
$this->crawlProfile = function (CrawlerUrl $url) { |
49
|
|
|
return $url->host == CrawlerUrl::create($this->url)->host; |
50
|
|
|
}; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function setUrl(string $url) |
54
|
|
|
{ |
55
|
|
|
$this->url = $url; |
56
|
|
|
|
57
|
|
|
return $this; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function hasCrawled(callable $hasCrawled) |
61
|
|
|
{ |
62
|
|
|
$this->hasCrawled = $hasCrawled; |
63
|
|
|
|
64
|
|
|
return $this; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @return \Spatie\Sitemap\Sitemap |
69
|
|
|
*/ |
70
|
|
|
public function getSitemap() |
71
|
|
|
{ |
72
|
|
|
$this->crawler |
73
|
|
|
->setCrawlProfile($this->getProfile()) |
74
|
|
|
->setCrawlObserver($this->getObserver()) |
75
|
|
|
->startCrawling($this->url); |
76
|
|
|
|
77
|
|
|
return $this->sitemap; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
public function writeToFile($path) |
81
|
|
|
{ |
82
|
|
|
$this->getSitemap()->writeToFile($path); |
83
|
|
|
|
84
|
|
|
return $this; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
protected function getObserver(): Observer |
88
|
|
|
{ |
89
|
|
|
$performAfterUrlHasBeenCrawled = function (CrawlerUrl $crawlerUrl) { |
90
|
|
|
$sitemapUrl = ($this->hasCrawled)(Url::create((string) $crawlerUrl)); |
91
|
|
|
|
92
|
|
|
if ($sitemapUrl) { |
93
|
|
|
$this->sitemap->add($sitemapUrl); |
94
|
|
|
} |
95
|
|
|
}; |
96
|
|
|
|
97
|
|
|
return new Observer($performAfterUrlHasBeenCrawled); |
98
|
|
|
} |
99
|
|
|
|
100
|
|
|
protected function getProfile(): Profile |
101
|
|
|
{ |
102
|
|
|
return new Profile($this->crawlProfile); |
103
|
|
|
} |
104
|
|
|
} |
105
|
|
|
|