-
-
Save saltybeagle/3532769 to your computer and use it in GitHub Desktop.
Simple, configureable and lightweight Spam Detector
This file contains hidden or 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 | |
$spamChecker = new SpamChecker(); | |
$spamChecker->addRule(function($spam){ | |
if (strpos($spam, 'test') !== false) { | |
return true; | |
} | |
}); | |
echo "The following should be true" . PHP_EOL; | |
var_dump($spamChecker->isSpam('this is a test')); | |
echo "The following should be false" . PHP_EOL; | |
var_dump($spamChecker->isSpam('hello')); | |
class SpamChecker | |
{ | |
protected $rules = array(); | |
/** | |
* Checks the variable for spam. | |
* | |
* @prams string $potentialSpam can be any of the following: | |
* -text | |
* -ip address | |
* -User Agent | |
* -URL | |
*/ | |
function isSpam($potentialSpam) | |
{ | |
$type = $this->determineType($potentialSpam); | |
//Do we have rules set for this type? | |
if (!isset($this->rules[$type]) || !is_array($this->rules[$type])) { | |
return false; | |
} | |
//Check if this is spam | |
foreach ($this->rules[$type] as $rule) { | |
if ($rule($potentialSpam)) { | |
return true; | |
} | |
} | |
return false; | |
} | |
/** | |
* Determines the type of potential spam to test against. | |
* | |
* @throws Exception | |
* | |
* @param $potentialSpam | |
* | |
* @return String ('text'|'ip'|'ua'|'url') | |
*/ | |
function determineType($potentialSpam) | |
{ | |
if (!is_string($potentialSpam)) { | |
throw new Exception('String Required'); | |
} | |
//regex to determine type of spam | |
//If nothing else, it is just text. | |
return "text"; | |
} | |
/** | |
* Adds a rule of a given type. | |
* | |
* @throws Exception | |
* | |
* @param $rule Function | |
* @param $ruleType String ('text'|'ip'|'ua'|'url') | |
* | |
* @return self | |
*/ | |
function addRule($rule, $ruleType = 'text') | |
{ | |
$ruleType = strtolower($ruleType); | |
if (!in_array($ruleType, array('text', 'ip', 'ua', 'url'))) { | |
throw new Exception("Rule types can be 'text', 'ip', 'ua' or 'url'"); | |
} | |
if (!is_callable($rule)) { | |
throw new Exception("The rule must be a function"); | |
} | |
$this->rules[$ruleType][] = $rule; | |
return $this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment