1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
<?php
namespace oroboros\core\abstracts\libraries\validation;
abstract class AbstractValidator
extends \oroboros\core\abstracts\libraries\manager\AbstractManager
implements \oroboros\core\interfaces\api\ValidationApi
{
const CLASS_SCOPE = \oroboros\core\interfaces\api\ClassScopeApi::CLASS_SCOPE_LIBRARY_ABSTRACT;
const API = '\\oroboros\\core\\interfaces\\api\\ValidationApi';
const DEFAULT_WORKER = FALSE;
private $_workers = array(
'database' => 'workers\\DatabaseValidator'
);
private $_worker;
public function __construct(array $params = array(), array $flags = array()) {
if (self::DEFAULT_WORKER) {
$this->_registerWorker('default', self::DEFAULT_WORKER);
$this->_worker = $this->_getWorker('default');
}
parent::__construct($params, $flags);
}
public function initialize(array $params = array(), array $flags = array()) {
if (array_key_exists('workers', $params)) {
$this->_registerWorkers($params['workers']);
unset($params['workers']);
}
if (self::DEFAULT_WORKER) {
$this->_worker = $this->_getWorker(self::DEFAULT_WORKER);
} elseif (array_key_exists('mode', $params)) {
$this->_worker = $this->_getWorker($params['mode']);
}
parent::initialize($params, $flags);
}
public function validate($data, array $schema) {
return $this->_worker->validate($data, $schema);
}
public function mode($mode) {
$this->_worker = $this->_getWorker($mode);
return $this;
}
protected function _registerWorker($worker, $resource) {
$this->_workers[$worker] = $resource;
}
protected function _registerWorkers(array $workers) {
foreach ($workers as $worker => $resource) {
$this->_registerWorker($worker, $resource);
}
}
private function _getWorker($worker = NULL) {
if (!isset($worker)) {
return $this->_worker;
}
if (!array_key_exists($worker, $this->_workers)) {
throw new \oroboros\core\utilities\exception\Exception("Invalid validation worker: [" . (string) $worker . "]", self::ERROR_LOGIC_BAD_PARAMETERS);
}
try {
$namespace = substr(get_class($this), 0, strrpos(get_class($this), '\\'));
$class = $namespace . '\\' . $this->_workers[$worker];
$workerObject = new $class();
return $workerObject;
} catch (\Exception $e) {
$this->_log(self::WARNING, "Failed to load validation worker: [" . (string) $worker . ']' . PHP_EOL . '-->Referenced in [:: ' . get_class($this) . ' ::]' . PHP_EOL . '-->[:: Backtrace ::]' . PHP_EOL . '--> ' . $e->getTraceAsString() . PHP_EOL);
throw new \oroboros\core\utilities\exception\Exception("Could not load worker: [" . (string) $worker . "]", self::ERROR_LOGIC, $e);
}
}
}