Skip to content

Instantly share code, notes, and snippets.

@mfairchild365
Created August 30, 2012 16:19
Show Gist options
  • Save mfairchild365/3532182 to your computer and use it in GitHub Desktop.
Save mfairchild365/3532182 to your computer and use it in GitHub Desktop.
Simple, configureable and lightweight Spam Detector
<?php
$spamChecker = new SpamChecker();
$spamChecker->addRule('text', 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 $ruleType String ('text'|'ip'|'ua'|'url')
* @param $rule Function
*/
function addRule($ruleType, $rule)
{
$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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment