-
-
Save anonymous/3f7bd7dd879ac7bf0cd8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class LatestSearches { | |
private $max = 25; | |
private $filename; | |
private $dom; | |
public function __construct($file) { | |
if(file_exists($file) && is_writable($file)) { | |
$this->dom = new DOMDocument(); | |
if(!@$this->dom->load($file)) { | |
throw new Exception('"'.$file.'" is not a valid XML file'); | |
} else { | |
$this->filename = $file; | |
} | |
} else { | |
throw new Exception('"'.$file.'" does not exists or is not writable.'); | |
} | |
} | |
public function addSearch($searchString) { | |
$searchNode = $this->dom->createElement('search', $searchString); | |
$this->dom->getElementsByTagName('searches')->item(0)->appendChild($searchNode); | |
if($this->countEntries() > $this->max) { | |
$firstSearchNode = $this->dom->getElementsByTagName('search')->item(0); | |
$this->dom->getElementsByTagName('searches')->removeChild($firstSearchNode); | |
} | |
$this->dom->save($this->filename); | |
} | |
public function getLatestSearches($max = 25, $latestFirst = true) { | |
$searches = array(); | |
$nbEntries = $this->countEntries(); | |
$i = 0; | |
while($i < $nbEntries && $i < $max) { | |
$searches[] = $this->dom->getElementsByTagName('search')->item($i)->firstChild->nodeValue; | |
$i++; | |
} | |
if($latestFirst == true) { | |
$searches = array_reverse($searches); | |
} | |
return $searches; | |
} | |
public function countEntries() { | |
return $this->dom->getElementsByTagName('search')->length; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment