Skip to content

Commit 60d18aa

Browse files
committed
Fixed buggy parsing and switched to serialized cache
1 parent 1f97a2e commit 60d18aa

File tree

1 file changed

+16
-16
lines changed

1 file changed

+16
-16
lines changed

bashquote

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ if ($proxy = str_replace("http://", "tcp://", getenv('http_proxy')))
77

88
$quotes = new BashOrgQuotes();
99
$quote = $quotes->getQuote();
10-
$quote = $quotes::cleanupQuote($quote);
1110
echo $quote."\n";
1211

1312
/**
@@ -50,7 +49,7 @@ abstract class Quotes {
5049
* Read the cache contents
5150
*/
5251
function cacheRead() {
53-
$cache = file($this->quotefile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES | FILE_TEXT);
52+
$cache = unserialize(file_get_contents($this->quotefile));
5453
if ($cache) {
5554
$this->quotes = $cache;
5655
} else {
@@ -63,7 +62,7 @@ abstract class Quotes {
6362
* Write the cache contents to disk
6463
*/
6564
function cacheWrite() {
66-
if (FALSE === file_put_contents($this->quotefile, implode("\n", $this->quotes))) {
65+
if (FALSE === file_put_contents($this->quotefile, serialize($this->quotes))) {
6766
throw new Exception('Could not write quote cache');
6867
}
6968
}
@@ -87,6 +86,7 @@ abstract class Quotes {
8786
}
8887
return $quote;
8988
}
89+
9090
}
9191

9292
/**
@@ -96,23 +96,23 @@ abstract class Quotes {
9696
*/
9797
class BashOrgQuotes extends Quotes {
9898

99-
function fetchQuotes() { // */p[@class='qt']
100-
$matches = array();
101-
$source = file_get_contents("http://bash.org/?random1");
102-
// @todo Handle failure
103-
preg_match_all("/<p class=\"qt\">(.+?)<\/p>/si", $source, $matches);
99+
/**
100+
* Fetch and parse a batch of random quotes from bash.org
101+
*/
102+
function fetchQuotes() {
103+
libxml_use_internal_errors(TRUE);
104+
$doc = DOMDocument::loadHTMLFile("http://bash.org/?random1");
105+
$xpath = new DOMXPath($doc);
106+
$elements = $xpath->query('//p[@class="qt"]');
104107
$quotes = array();
105-
foreach ($matches[1] as $match) {
106-
$quotes[] = str_replace("\n","",$match);
108+
foreach ($elements as $element) {
109+
$quote = $element->textContent;
110+
$quote = html_entity_decode($quote);
111+
$quote = str_replace("<br />", "\n", $quote);
112+
$quotes[] = $quote;
107113
}
108114
return $quotes;
109115
}
110-
111-
static function cleanupQuote($quote) {
112-
$quote = html_entity_decode($quote);
113-
$quote = str_replace("<br />","\n",$quote);
114-
return $quote;
115-
}
116116
}
117117

118118
?>

0 commit comments

Comments
 (0)