-
Notifications
You must be signed in to change notification settings - Fork 0
/
bunburizador.php
103 lines (89 loc) · 2.34 KB
/
bunburizador.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
interface Ibunburizador {
public function getUrl();
}
abstract class bunburizador_abstract {
const NUM_PAGES = 3;
protected $language;
protected $phrases = array();
protected function __construct($language) {
$this->language = $language;
}
static public function factory($language = "es") {
$bunburizador = null;
switch($language) {
case 'es':
$bunburizador = new bunburizador($language);
break;
case 'en':
$bunburizador = new nirvanizer($language);
break;
default:
throw new Exception("Language not supported");
}
return $bunburizador;
}
protected function getText($page) {
$myPage = new DOMDocument();
$myPage->loadHTML($page);
$myPageElements = $myPage->getElementById("bodyContent");
$nodeList = $myPageElements->getElementsByTagName("p");
$phrases = array();
foreach($nodeList as $node) {
$phrases[] = $node->nodeValue;
}
return $phrases;
}
protected function getParsedPage() {
$page = file_get_contents($this->getUrl());
$phrases = $this->getText($page);
$songPhrases = array();
foreach($phrases as $phrase) {
$dotPhrases = explode(".", $phrase);
foreach($dotPhrases as $dotPhrase) {
$commaPhrases = explode(",", $dotPhrase);
$songPhrases = array_merge($songPhrases, $commaPhrases);
}
}
return $songPhrases;
}
protected function purgePhrases() {
$phrases = array();
foreach($this->phrases as $phrase) {
if(preg_match("/\[.\]/", $phrase)) {
}
else {
$phrases[] = $phrase;
}
}
$this->phrases = $phrases;
return $this;
}
protected function getPages() {
$this->phrases = array();
for($i = 0; $i < self::NUM_PAGES; $i++) {
$this->phrases = array_merge($this->phrases, $this->getParsedPage());
}
return $this;
}
public function getSong() {
$this->getPages()->purgePhrases();
$randomPhrases = rand(6, 30);
$song = '';
for($i = 0; $i < $randomPhrases; $i++) {
$randomPhrase = rand(0, count($this->phrases));
$song .= $this->phrases[$randomPhrase]."\n";
}
return $song;
}
}
class bunburizador extends bunburizador_abstract implements Ibunburizador {
public function getUrl() {
return "http://es.wikipedia.org/wiki/Especial:Aleatoria";
}
}
class nirvanizer extends bunburizador_abstract implements Ibunburizador {
public function getUrl() {
return "http://en.wikipedia.org/wiki/Special:Random";
}
}