Skip to content

Instantly share code, notes, and snippets.

@xappz
Last active April 14, 2017 10:06
Show Gist options
  • Save xappz/fdd9b0131234591ce945cde29b3a31e2 to your computer and use it in GitHub Desktop.
Save xappz/fdd9b0131234591ce945cde29b3a31e2 to your computer and use it in GitHub Desktop.
Roll your own PHP validator
<?php
error_reporting(-1);
require_once("vendor/autoload.php");
use \Utils\Validator as V;
main();
function main()
{
V::validate([
['field' => 'http://www.google.com', 'alias' => 'URL', 'rules' => [V::IS_URL]],
['field' => 'v1', 'alias' => 'value', 'rules' => [V::IN_ARRAY], 'array' => ['v1', 'val2']]
]);
}
<?php
namespace Utils;
class Validator {
const IS_URL = 1;
const IN_ARRAY = 2;
//other constants
public static function validate($fields) {
foreach ($fields as $f) {
//we need field, alias and rules for each value to be checked
if (!array_key_exists('field', $f)) {
throw new \Exception('No field specified'); }
if (!array_key_exists('alias', $f)) {
throw new \Exception('No alias specified'); }
if (!array_key_exists('rules', $f)) {
throw new \Exception('No rules specified');
}
foreach ($f['rules'] as $r) {
static::check($f, $r);
}
}
}
private static function check($f, $rule) {
switch ($rule) {
case static::IS_URL:
$url = filter_var($f['field'], FILTER_VALIDATE_URL);
if (!$url) {
throw new \Exception("Please provide valid {$f['alias']}");
}
break;
case static::IN_ARRAY:
if (!array_key_exists('array', $f)) {
throw new \Exception("No array specified");
}
if (!in_array($f['field'], $f['array'])) {
throw new \Exception("Please specify valid value for {$f['alias']}!");
}
break;
//other rules
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment