static function error($details = '') { if (!is_scalar($details)) { Debug::toss($details); } else { throw new \Exception($details); } }
static function __callStatic($name, $arguments) { if (!method_exists(__CLASS__, $name)) { Debug::toss('DbBatch method not found: ' . $name); } $class = __CLASS__; $that = new $class(); return call_user_func_array(array($that, $name), $arguments); }
static function checkLoggedIn($html, $login) { $matches = array('@log\\s?(out|off)@i', '@sign\\s?(out|off)@i', '@Last Month|Last Week@i', '@[^a-z]My [a-z]@i', '@[ >]Scoop Interactive[< ]@i'); foreach ($matches as $match) { if (preg_match($match, $html)) { return true; } } Debug::out('||ERROR||: Could not login'); Debug::out($login); return false; }
function __call($fnName, $args) { if (method_exists($this, $fnName)) { return call_user_func_array(array($this, $fnName), $args); } elseif (method_exists($this->under, $fnName)) { return call_user_func_array(array($this->under, $fnName), $args); } elseif (method_exists($this->under, '__call')) { //under may have it's own __call handling return call_user_func_array(array($this->under, $fnName), $args); } Debug::toss(__CLASS__ . ' Method not found: ' . $fnName); }
static function json_encode($x, $options = 0, $depth = 512) { $json = json_encode($x, $options, $depth); if ($json === false) { if (json_last_error() == JSON_ERROR_UTF8) { self::utf8_encode($x); $json = json_encode($x, $options, $depth); } } if (json_last_error() != JSON_ERROR_NONE) { $types = [JSON_ERROR_NONE => 'JSON_ERROR_NONE', JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH', JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH', JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR', JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX', JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8', JSON_ERROR_RECURSION => 'JSON_ERROR_RECURSION', JSON_ERROR_INF_OR_NAN => 'JSON_ERROR_INF_OR_NAN', JSON_ERROR_UNSUPPORTED_TYPE => 'JSON_ERROR_UNSUPPORTED_TYPE']; Debug::toss('JSON encode error: ' . $types[json_last_error()]); } return $json; }
static function loadXml($xml, $nsPrefix = 'd') { $dom = new \DOMDocument(); @$dom->loadXML($xml); $xpath = new \DomXPath($dom); $rootNamespace = $dom->lookupNamespaceUri($dom->namespaceURI); if ($rootNamespace) { if ($dom->documentElement->getAttribute('xmlns:d')) { Debug::toss('Namespace prefix "' . $nsPrefix . '" taken'); } $xpath->registerNamespace($nsPrefix, $rootNamespace); $nsPrefix .= ':'; } else { $nsPrefix = ''; } return array($dom, $xpath, $nsPrefix); }
<?php $base = realpath(__DIR__ . '/../'); # Assumes composer used require $base . '/vendor/autoload.php'; use Grithin\Route; $route = new Route(['folder' => $base . '/control/']); /** Based on the controls and the routes, will handle the following paths: - / - /bill/123 - /staticMethod - /instanceMethod - /globalFunction - /index - /test/normal */ try { $route->handle(); } catch (RouteException $e) { \Grithin\Debug::out('Route exception encountered'); \Grithin\Debug::out($route); throw $e; }
<?php \Grithin\Debug::out(['Tokens:', $route->tokens]); \Grithin\Debug::quit('Loaded Control: ' . __FILE__);
/** @param options { mimic:<return paths prefixes with @:dir>, prefix:<prefix returned file paths with>, filter:<function to filter returned paths>, ghost:<don't error on non-existent>} */ static function scan($dir, $options = []) { if (!$options['prefix'] && $options['mimic']) { $options['prefix'] = $dir; } if (isset($options['maxDepth']) && $options['maxDepth'] == 0) { return []; } $realPath = realpath($dir); if (!$realPath) { if ($options['ghost']) { return []; } else { Debug::toss('No such directory'); } } $realPath .= '/'; $files = array(); foreach (scandir($realPath) as $v) { if ($v != '.' && $v != '..') { if (is_dir($realPath . $v)) { $newOptions = array_merge($options, ['prefix' => $options['prefix'] . $v . '/']); if (isset($newOptions['maxDepth'])) { $newOptions['maxDepth']--; } $newFiles = self::scan($realPath . $v, $newOptions); $files = Arrays::merge($files, $newFiles); } else { if (!$options['filter'] || $options['filter']($options['prefix'] . $v)) { $files[] = $options['prefix'] . $v; } } } } return $files; }
function checkUniqueKeys($value, $table, $type, $id = null) { $indices = $this->db->indices($table); foreach ($indices as $name => $key) { if ($key['unique']) { if ($name != 'PRIMARY') { foreach ($key['columns'] as $column) { if (!isset($this->input->in[$column]) || $this->input->in[$column] === null) { //null indices can overlap continue 2; } } $where = Arrays::extract($key['columns'], $this->input->in); if ($type != 'create' && $id) { $where['id?<>'] = $id; } if ($this->db->check($table, $where)) { Debug::toss(['type' => 'record_not_unique', 'detail' => $key['columns']], 'InputException'); } } } } }
function instancely($route) { \Grithin\Debug::out([$route->regexMatch, $route->tokens]); \Grithin\Debug::quit('Route Rule Function Called'); }
/** @param table table to replace on @param where see self::where() function @return row count @note as a precaution, to delete all must use $where = '1 = 1' */ protected function delete($table, $where) { if (!$where) { Debug::toss('Unqualified delete is too risky. Use 1=1 to verify'); } return $this->query('DELETE FROM ' . $this->quoteIdentity($table) . $this->where($where))->rowCount(); }
function apply_rules($field, $rules) { try { $value = Arrays::got($this->input, $field); } catch (\Exception $e) { # Field wasn't found $value = null; } foreach ($rules as $rule) { # handle continuity if ($rule['flags']['continuity'] && $this->field_errors($field)) { Debug::toss(['type' => 'continuity']); } elseif ($rule['flags']['full_continuity'] && $this->errors) { Debug::toss(['type' => 'continuity']); } # resolve and try function $fn = $this->resolve_fn($rule['fn_path']); $params = array_merge([$value], $rule['params']); # including `input` and `output` as referenced arrays doubles the time of a do-nothing callback $params[] = ['field' => $field, 'instance' => $this]; try { $value = call_user_func_array($fn, $params); if ($rule['flags']['not']) { Debug::toss(['type' => 'not']); } } catch (\Exception $e) { $error = self::parse_exception($e); if ($rule['flags']['not'] && $error['type'] != 'not') { # potentially, the not flag caused the Error continue; } if (!$rule['flags']['optional']) { $error['rule'] = $rule; $this->error($error, $field); } if ($rule['flags']['break']) { $error['type'] = 'break'; Debug::toss($error); } if ($rule['flags']['break_all']) { $error['type'] = 'break_all'; Debug::toss($error); } } } return $value; }
'clicks' : 2 ] */ Debug::out($conform->standardise_errors()); /* 0 : [ 'fields' : [ 0 : 'hits' ] 'message' : 'v.int' 'rule' : [ 'flags' : [] 'params' : [] 'fn_path' : 'v.int' ] 'type' : 'v.int' 'params' : [] ] ] */ # Clearing previous errors and output $conform->clear(); # rules which always pass $rules = ['hits' => 'f.int', 'clicks' => '']; Debug::out($conform->fields_rules($rules)); /* [ 'hits' : 0 'clicks' : 2 ] */
/** adds file and rules to ruleSets and parses all active rules in current file and former files @param path str file location string */ function matchRules($path, &$rules) { foreach ($rules as $ruleKey => &$rule) { if (!$rule) { # rule may have been flagged "once" continue; } unset($matched); if (!isset($rule['flags'])) { $flags = $rule[2] ? explode(',', $rule[2]) : array(); $rule['flags'] = array_fill_keys(array_values($flags), true); //parse flags for determining match string if ($rule['flags']['regex']) { $rule['matcher'] = \Grithin\Strings::pregDelimit($rule[0]); if ($rule['flags']['caseless']) { $rule['matcher'] .= 'i'; } } else { if ($rule['flags']['caseless']) { $rule['matcher'] = strtolower($rule[0]); } else { $rule['matcher'] = $rule[0]; } } } if ($rule['flags']['caseless']) { $subject = $this->caselessPath; } else { $subject = $this->path; } //test match if ($rule['flags']['regex']) { if (preg_match($rule['matcher'], $subject, $this->regexMatch)) { $matched = true; } } else { if ($rule['matcher'] == $subject) { $matched = true; } } if ($matched) { if ($this->debug) { Debug::log(['Matched Rule', $rule], ['title' => 'Route']); } $this->matchedRules[] = $rule; //++ apply replacement logic { if ($rule['flags']['regex']) { if (is_callable($rule[1])) { $this->matcher = $rule['matcher']; $bound = new Bound($rule[1], [$this]); } else { $bound = new Bound('\\Grithin\\Route::regexReplacer', [$rule[1]]); } $replacement = preg_replace_callback($rule['matcher'], $bound, $this->path, 1); } else { if (is_callable($rule[1])) { $this->matcher = $rule['matcher']; $replacement = call_user_func($rule[1], $this); } else { $replacement = $rule[1]; } } //handle redirects if ($rule['flags'][301]) { $httpRedirect = 301; } if ($rule['flags'][303]) { $httpRedirect = 303; } if ($rule['flags'][307]) { $httpRedirect = 307; } if ($httpRedirect) { if ($rule['flags']['params']) { $replacement = Http::appendsUrl(Http::parseQuery($_SERVER['QUERY_STRING']), $replacement); } Http::redirect($replacement, 'head', $httpRedirect); } //remake url with replacement $this->applyPath($replacement); $this->parsedTokens = []; $this->unparsedTokens = array_merge([''], $this->tokens); //++ } //++ apply parse flag { if ($rule['flags']['once']) { $rules[$ruleKey] = null; } elseif ($rule['flags']['file:last']) { $this->ruleSets[$path] = []; } elseif ($rule['flags']['last']) { $this->unparsedTokens = []; } //++ } return true; } } unset($rule); return false; }
function __methodExists($fnName) { if (!method_exists($this, $fnName)) { Debug::toss(get_called_class() . ' Method not found: ' . $fnName); } }
function ruleCallable($callback) { if (is_string($callback)) { list($type, $method) = explode('.', $callback, 2); if (!$method) { $method = $type; unset($type); } } else { return $callback; } if (!$callback) { \Grithin\Debug::toss('Failed to provide callback for input handler'); } switch ($type) { case 'f': case 'filter': return [$this->filter, $method]; break; case 'v': case 'validate': return [$this->validate, $method]; break; case 'l': case 'local': list($name, $method) = explode('.', $method, 2); return [$this->localInstances[$name], $method]; break; case 'g': case 'global': return $method; break; default: if ($type) { return [$type, $method]; } return $callback; break; } }