public function __call($event, $args) { if (substr($event, 0, 3) == 'get') { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($event, 3))); $key = Inflector::lower($uncamelizeMethod); return self::get($key); } elseif (substr($event, 0, 3) == 'set') { $value = Arrays::first($args); $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($event, 3))); $key = Inflector::lower($uncamelizeMethod); return self::set($key, $value); } if (true === self::__has($event)) { return self::__fire($event, $args); } else { $value = Arrays::first($args); if ($value instanceof Closure) { $eventable = self::__event($event, $value); } else { $set = function () use($value) { return $value; }; $eventable = self::__event($event, $set); } } }
public function __call($event, $args) { if (substr($event, 0, 3) == 'get' && strlen($event) > 3) { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($event, 3))); $key = Inflector::lower($uncamelizeMethod); return $this->get($key); } elseif (substr($event, 0, 3) == 'set' && strlen($event) > 3) { $value = Arrays::first($args); $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($event, 3))); $key = Inflector::lower($uncamelizeMethod); return $this->set($key, $value); } if (true === $this->__has($event)) { array_push($args, $this); return $this->__fire($event, $args); } else { if (method_exists($this, $event)) { throw new Exception("The method {$event} is a native class' method. Please choose an other name."); } $value = Arrays::first($args); if ($value instanceof Closure) { $eventable = $this->__event($event, $value); } else { $set = function () use($value) { return $value; }; $eventable = $this->__event($event, $set); } return $this; } }
public function __call($func, $argv) { if (substr($func, 0, 3) == 'get' && strlen($func) > 3) { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, 3))); $var = Inflector::lower($uncamelizeMethod); if (isset($this->{$var})) { $this->clean(); return $this->{$var}; } else { return null; } } elseif (substr($func, 0, 3) == 'set' && strlen($func) > 3) { $value = $argv[0]; $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, 3))); $var = Inflector::lower($uncamelizeMethod); $this->{$var} = $value; return $this->save(); } elseif (substr($func, 0, 6) == 'forget' && strlen($func) > 6) { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, 6))); $var = Inflector::lower($uncamelizeMethod); $this->erase($var); return $this->save(); } $id = sha1($func); if (isset($this->{$id})) { if ($this->{$id} instanceof \Closure) { return call_user_func_array($this->{$id}, $argv); } } if (!is_callable($func) || substr($func, 0, 3) !== 'set' || substr($func, 0, 3) !== 'get') { throw new \BadMethodCallException(__CLASS__ . ' => ' . $func); } }
public function __destruct() { /* On efface le model de la base tampon et on vide la base */ $modelFile = APPLICATION_PATH . DS . 'models' . DS . 'Bigdata' . DS . 'models' . DS . Inflector::lower($this->to->db) . DS . ucfirst(Inflector::lower($this->to->table)) . '.php'; File::delete($modelFile); $this->to->drop(); }
public static function __callStatic($fn, $args) { $method = Inflector::upper($fn); if (count($args) < 2) { throw new Exception("You must provide at least a path and a mvc pattern."); } $path = $args[0]; $mvc = $args[1]; $argsRoute = []; $optionsRoute = []; if (count($args) > 2) { $argsRoute = $args[2]; if (count($args) > 3) { array_shift($args); array_shift($args); array_shift($args); $optionsRoute = $args; } } list($module, $controller, $action) = explode('::', $mvc, 3); if (!isset($module) || !isset($controller) || !isset($action)) { throw new Exception("MVC '{$mvc}' is incorrect."); } return ['name' => Inflector::lower($method) . '::' . $module . '::' . $controller . '::' . $action, 'method' => $method, 'path' => $path, 'module' => $module, 'controller' => $controller, 'action' => $action, 'args' => $argsRoute, 'options' => $optionsRoute]; }
public static function callback($class, $method, Closure $cb) { $callbackClass = ucfirst(Inflector::lower($class)); if (!class_exists('Thin\\' . $callbackClass)) { eval("namespace Thin; class {$callbackClass} extends Alias {}"); } static::$cb[$callbackClass][$method] = $cb; }
public function register() { $args = func_get_args(); if (count($args) < 1 || count($args) > 1) { throw new Exception("You need to provide a helper to register."); } $helper = reset($args); $this->type = 'helpers'; $this->file = APPLICATION_PATH . DS . 'helpers' . DS . ucfirst(Inflector::lower($helper)) . DS . ucfirst(Inflector::lower($helper)) . '.php'; $this->class = 'ThinHelper\\' . ucfirst(Inflector::lower($helper)) . '\\' . ucfirst(Inflector::lower($helper)); return $this->factory(); }
function run($lib, $args = null) { $lib = Inflector::lower(Inflector::uncamelize($lib)); $script = str_replace('_', DS, $lib) . '.php'; if (fnmatch('*_*', $lib)) { $class = 'Thin\\' . str_replace('_', '\\', $lib); $tab = explode('\\', $class); $first = $tab[1]; $class = str_replace('Thin\\' . $first, 'Thin\\' . ucfirst($first) . 'Libs', $class); if (count($tab) > 2) { for ($i = 2; $i < count($tab); $i++) { $seg = trim($tab[$i]); $class = str_replace('\\' . $seg, '\\' . ucfirst($seg), $class); } } } else { $class = 'Thin\\' . ucfirst($lib) . 'Libs'; } $file = __DIR__ . DS . 'libs' . DS . $script; if (is_file($file)) { require_once $file; if (empty($args)) { return new $class(); } else { if (!is_array($args)) { if (is_string($args)) { if (fnmatch('*,*', $args)) { $args = explode(',', str_replace(', ', ',', $args)); } else { $args = [$args]; } } else { $args = [$args]; } } $methods = get_class_methods($class); if (in_array('instance', $methods)) { return call_user_func_array([$class, 'instance'], $args); } else { return construct($class, $args); } } } if (class_exists('Thin\\' . $lib)) { $c = 'Thin\\' . $lib; return new $c(); } if (class_exists($lib)) { return new $lib(); } throw new Exception("The library {$class} does not exist."); }
public static function make($db, $what) { if (is_string($what)) { $file = APPLICATION_PATH . DS . 'models' . DS . 'Bigdata' . DS . 'views' . DS . $db->db . DS . ucfirst(I::lower($db->table)) . DS . I::camelize($what) . '.php'; if (files()->exists($file)) { require_once $file; $class = '\\Thin\\' . ucfirst(I::lower($db->db)) . ucfirst(I::lower($db->table)) . 'View'; return $class::make($db); } else { return $db; } } elseif (A::is($what)) { $nameview = 'view_' . $db->db . '_' . $db->table . '_' . sha1(serialize($what)); $ageDb = $db->getage(); $viewDb = Db::instance($db->db, $nameview); $ageView = $db->getage(); $exists = strlen($db->cache()->get('dbRedis.views.' . $nameview)) ? true : false; if ($ageView < $ageDb || !$exists) { $viewDb->getCollection()->remove(); foreach ($what as $wh) { $op = 'AND'; if (count($wh) == 4) { $op = $wh[3]; unset($wh[3]); } $db = $db->where($wh); } $res = $db->exec(); foreach ($res as $row) { $viewDb->saveView($row); } $db->cache()->set('dbRedis.views.' . $nameview, 1); } return $viewDb; } }
private function compare($comp, $op, $value) { $res = false; if (strlen($comp) && strlen($op) && strlen($value)) { $comp = Inflector::lower(Inflector::unaccent($comp)); $value = Inflector::lower(Inflector::unaccent($value)); switch ($op) { case '=': $res = sha1($comp) == sha1($value); break; case '>=': $res = $comp >= $value; break; case '>': $res = $comp > $value; break; case '<': $res = $comp < $value; break; case '<=': $res = $comp <= $value; break; case '<>': case '!=': $res = sha1($comp) != sha1($value); break; case 'LIKE': $value = str_replace("'", '', $value); $value = str_replace('%', '*', $value); $res = fnmatch($value, $comp); break; case 'NOTLIKE': $value = str_replace("'", '', $value); $value = str_replace('%', '*', $value); $check = fnmatch($value, $comp); $res = !$check; break; case 'LIKESTART': $value = str_replace("'", '', $value); $value = str_replace('%', '', $value); $res = substr($comp, 0, strlen($value)) === $value; break; case 'LIKEEND': $value = str_replace("'", '', $value); $value = str_replace('%', '', $value); if (!strlen($comp)) { $res = true; } $res = substr($comp, -strlen($value)) === $value; break; case 'IN': $value = str_replace('(', '', $value); $value = str_replace(')', '', $value); $tabValues = explode(',', $value); $res = Arrays::in($comp, $tabValues); break; case 'NOTIN': $value = str_replace('(', '', $value); $value = str_replace(')', '', $value); $tabValues = explode(',', $value); $res = !Arrays::in($comp, $tabValues); break; } } return $res; }
private function makeResults($fetch = true) { if (count($this->fields)) { $pk = "{$this->database}.{$this->table}." . $this->pk(); $hasPk = false; $select = ''; foreach ($this->fields as $field) { if (false === $hasPk) { $hasPk = $field == $pk; } list($db, $table, $tmpField) = explode('.', $field, 3); $as = isAke($this->as, $field, null); if ($db == $this->database && $table == $this->table) { if (is_null($as)) { $select .= "{$field}, "; } else { $select .= "{$field} AS {$as}, "; } } else { if (is_null($as)) { $select .= "{$field} AS " . 'join_' . str_replace('.', '_', Inflector::lower($field)) . ", "; } else { $select .= "{$field} AS {$as}, "; } } } if (false === $hasPk) { $select .= "{$pk}, "; } } else { $fields = array_keys($this->map['fields']); $select = ''; foreach ($fields as $field) { $select .= "{$this->database}.{$this->table}.{$field}, "; } } $select = substr($select, 0, -2); if (!count($this->joins)) { $query = "SELECT {$select} FROM {$this->database}.{$this->table} WHERE "; } else { $query = "SELECT {$select} FROM {$this->database}.{$this->table} "; foreach ($this->joins as $join) { list($model, $condition, $type) = $join; $joinKey = $model->table . '_id'; $fpk = $model->pk(); if (is_null($condition)) { $query .= "{$type} JOIN {$model->database}.{$model->table} ON {$this->database}.{$this->table}.{$joinKey} = {$model->database}.{$model->table}.{$fpk}\n"; } else { $query .= "{$type} JOIN {$model->database}.{$model->table} ON {$condition}\n"; } } $query .= "WHERE\n"; } if (count($this->wheres)) { $first = true; foreach ($this->wheres as $where) { list($op, $condition) = $where; if (count($this->joins)) { $condition = repl('NOT LIKE', 'NOTLIKE', $condition); $condition = repl('NOT IN', 'NOTIN', $condition); list($field, $operator, $value) = explode(' ', $condition, 3); if ($value instanceof Container) { $value = $value->id(); $field = $field . '_id'; } if (!strstr($field, '.')) { $field = "{$this->database}.{$this->table}.{$field}"; } $condition = "{$field} {$operator} {$value}"; $condition = repl('NOTLIKE', 'NOT LIKE', $condition); $condition = repl('NOTIN', 'NOT IN', $condition); } if (false === $first) { $query .= " {$op} {$condition}"; } else { $query .= $condition; } $first = false; } } else { $query .= '1 = 1'; } if (count($this->groupBys)) { $query .= ' GROUP BY '; $first = true; foreach ($this->groupBys as $groupBy) { if (false === $first) { if (!strstr($groupBy, '.')) { $query .= ", {$this->database}.{$this->table}.{$groupBy}"; } else { $query .= ", {$groupBy}"; } } else { if (!strstr($groupBy, '.')) { $query .= "{$this->database}.{$this->table}.{$groupBy}"; } else { $query .= $groupBy; } } $first = false; } } if (count($this->havings)) { $sql = array(); foreach ($query->havings as $having) { $sql[] = 'AND ' . $having['column'] . ' ' . $having['operator'] . ' ' . $having['value']; } $query .= 'HAVING ' . preg_replace('/AND /', '', implode(' ', $sql), 1); } if (count($this->orders)) { $query .= ' ORDER BY '; $first = true; foreach ($this->orders as $order) { list($field, $direction) = $order; if (false === $first) { if (!strstr($field, '.')) { $query .= ", {$this->database}.{$this->table}.{$field} {$direction}"; } else { $query .= ", {$field} {$direction}"; } } else { if (!strstr($field, '.')) { $query .= "{$this->database}.{$this->table}.{$field} {$direction}"; } else { $query .= "{$field} {$direction}"; } } $first = false; } } if (isset($this->limit)) { $offset = isset($this->offset) ? $this->offset : 0; $query .= ' LIMIT ' . $offset . ', ' . $this->limit; } $query = str_replace('WHERE 1 = 1', '', $query); $this->query = $query; if (true === $fetch) { if (true === $this->cache) { $cache = coreCache(); $key = sha1($query) . '::dataQuery'; $cached = $cache->get($key); if (!strlen($cached)) { $cached = $this->fetch($query); $cache->set($key, serialize($cached)); $cache->expire($key, Config::get('database.cache.ttl', 7200)); } else { $cached = unserialize($cached); } $this->results = $cached; } else { $this->results = $this->fetch($query); } } else { return $query; } return $this; }
public function __call($m, $a) { if (fnmatch('set*', $m)) { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, strlen('set')))); $field = Inflector::lower($uncamelizeMethod); if (!empty($a)) { $val = current($a); } else { $val = null; } $this->{$field} = $val; return $this; } elseif (fnmatch('get*', $m)) { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, strlen('set')))); $field = Inflector::lower($uncamelizeMethod); $default = count($a) == 1 ? current($a) : null; return isset($this->{$field}) ? $this->{$field} : $default; } else { return call_user_func_array([$this->_db], $a); } }
private function compare($comp, $op, $value) { $res = false; if (strlen($comp) && strlen($op) && !empty($value)) { if (is_numeric($comp)) { if (fnmatch('*,*', $comp) || fnmatch('*.*', $comp)) { $comp = floatval($comp); } else { $comp = intval($comp); } } if (is_numeric($value)) { if (fnmatch('*,*', $value) || fnmatch('*.*', $value)) { $value = floatval($value); } else { $value = intval($value); } } switch ($op) { case '=': $res = sha1($comp) == sha1($value); break; case '=i': $comp = Inflector::lower(Inflector::unaccent($comp)); $value = Inflector::lower(Inflector::unaccent($value)); $res = sha1($comp) == sha1($value); break; case '>=': $res = $comp >= $value; break; case '>': $res = $comp > $value; break; case '<': $res = $comp < $value; break; case '<=': $res = $comp <= $value; break; case '<>': case '!=': $res = sha1($comp) != sha1($value); break; case 'LIKE': $value = str_replace("'", '', $value); $value = str_replace('%', '*', $value); $res = fnmatch($value, $comp); break; case 'NOT LIKE': case 'NOTLIKE': $value = str_replace("'", '', $value); $value = str_replace('%', '*', $value); $check = fnmatch($value, $comp); $res = !$check; break; case 'BETWEEN': $res = $comp >= $value[0] && $comp <= $value[1]; break; case 'NOT BETWEEN': case 'NOTBETWEEN': $res = $comp < $value[0] || $comp > $value[1]; break; case 'LIKE START': case 'LIKESTART': $value = str_replace(["'", '%'], '', $value); $res = substr($comp, 0, strlen($value)) === $value; break; case 'LIKE END': case 'LIKEEND': $value = str_replace(["'", '%'], '', $value); if (!strlen($comp)) { $res = true; } $res = substr($comp, -strlen($value)) === $value; break; case 'IN': $value = str_replace('(', '', $value); $value = str_replace(')', '', $value); $tabValues = explode(',', $value); $res = in_array($comp, $tabValues); break; case 'NOT IN': case 'NOTIN': $value = str_replace('(', '', $value); $value = str_replace(')', '', $value); $tabValues = explode(',', $value); $res = !in_array($comp, $tabValues); break; } } return $res; }
public function __call($method, $parameters) { if (substr($method, 0, 6) == 'findBy') { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($method, 6))); $field = Inflector::lower($uncamelizeMethod); $value = Arrays::first($parameters); return $this->findBy($field, $value); } elseif (substr($method, 0, 9) == 'findOneBy') { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($method, 9))); $field = Inflector::lower($uncamelizeMethod); $value = Arrays::first($parameters); return $this->findBy($field, $value, true); } }
public function __call($method, $parameters) { if (substr($method, 0, 6) == 'findBy') { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($method, 6))); $field = Inflector::lower($uncamelizeMethod); $value = Arrays::first($parameters); return $this->findBy($field, $value); } elseif (substr($method, 0, strlen('findObjectsBy')) == 'findObjectsBy') { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($method, strlen('findObjectsBy')))); $field = Inflector::lower($uncamelizeMethod); $value = Arrays::first($parameters); return $this->findBy($field, $value, false, true); } elseif (substr($method, 0, 9) == 'findOneBy') { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($method, 9))); $field = Inflector::lower($uncamelizeMethod); $value = Arrays::first($parameters); return $this->findBy($field, $value, true); } else { $settings = isAke(self::$configs, $this->entity); $event = isAke($settings, $method); if (!empty($event)) { if (is_callable($event)) { if (version_compare(PHP_VERSION, '5.4.0', ">=")) { $event = $event->bindTo($this); } return call_user_func_array($event, $parameters); } } else { throw new Exception("The method '{$method}' is not callable."); } } }
public static function run() { Request::$route = $route = Utils::get('appDispatch'); container()->setRoute($route); $render = $route->getRender(); $tplDir = $route->getTemplateDir(); $module = $route->getModule(); $controller = $route->getController(); $action = $route->getAction(); $alert = $route->getAlert(); $page = container()->getPage(); $isCms = !empty($page); if (!empty($render)) { $tplMotor = $route->getTemplateMotor(); $tplDir = empty($tplDir) ? APPLICATION_PATH . DS . SITE_NAME . DS . 'app' . DS . 'views' : $tplDir; $tpl = $tplDir . DS . $render . '.phtml'; if (File::exists($tpl)) { if ('Twig' == $tplMotor) { if (!class_exists('Twig_Autoloader')) { require_once 'Twig/Autoloader.php'; } $tab = explode(DS, $tpl); $file = Arrays::last($tab); $path = repl(DS . $file, '', $tpl); $loader = new \Twig_Loader_Filesystem($path); $view = new \Twig_Environment($loader, array('cache' => CACHE_PATH, 'debug' => false, 'charset' => 'utf-8', 'strict_variables' => false)); container()->setView($view); if ($action instanceof Closure) { $action($view); } $params = null === container()->getViewParams() ? array() : container()->getViewParams(); echo $view->render($file, $params); /* stats */ if (null === container()->getNoShowStats() && null === $route->getNoShowStats()) { echo View::showStats(); } } else { $view = new View($tpl); container()->setView($view); if ($action instanceof Closure) { $action($view); } $view->render(); /* stats */ if (null === container()->getNoShowStats() && null === $route->getNoShowStats()) { echo View::showStats(); } } return; } } $module = Inflector::lower($module); $controller = Inflector::lower($controller); $action = Inflector::lower($action); if (true === container()->getMultiSite()) { $moduleDir = APPLICATION_PATH . DS . SITE_NAME . DS . 'modules' . DS . $module; } else { $moduleDir = APPLICATION_PATH . DS . 'modules' . DS . $module; } if (!is_dir($moduleDir)) { throw new Exception("The module '{$module}' does not exist."); } $controllerDir = $moduleDir . DS . 'controllers'; if (!is_dir($controllerDir)) { throw new Exception("The controller '{$controller}' does not exist."); } $controllerFile = $controllerDir . DS . $controller . 'Controller.php'; if (!File::exists($controllerFile)) { throw new Exception("The controller '{$controllerFile}' does not exist."); } require_once $controllerFile; $controllerClass = 'Thin\\' . $controller . 'Controller'; $controller = new $controllerClass(); $controller->view = new View($route->getView()); if (null !== $alert) { $controller->view->alert($alert); } container()->setController($controller); $actions = get_class_methods($controllerClass); if (true === $isCms) { if (!Arrays::inArray($action, $actions)) { $action = 'page'; } } container()->setAction($action); if (strstr($action, '-')) { $words = explode('-', $action); $newAction = ''; for ($i = 0; $i < count($words); $i++) { $word = trim($words[$i]); if ($i > 0) { $word = ucfirst($word); } $newAction .= $word; } $action = $newAction; } $actionName = $action . 'Action'; if (Arrays::in('init', $actions)) { $controller->init(); } if (Arrays::in('preDispatch', $actions)) { $controller->preDispatch(); } if (!Arrays::in($actionName, $actions)) { throw new Exception("The action '{$actionName}' does not exist."); } $controller->{$actionName}(); $controller->view->render(); if (Arrays::inArray('postDispatch', $actions)) { $controller->postDispatch(); } /* stats */ if (null !== Utils::get("showStats")) { echo View::showStats(); } }
public function __call($func, $argv) { $key = sha1('orm' . $this->_token); $orm = isAke($this->values, $key, false); $key = sha1('model' . $this->_token); $dbjson = isAke($this->values, $key, false); if (substr($func, 0, 4) == 'link' && false !== $orm) { $value = Arrays::first($argv); $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, 4))); $var = Inflector::lower($uncamelizeMethod); if (!empty($var)) { $var = setter($var . '_id'); $this->{$var}($value->id); return $this; } } elseif (substr($func, 0, 3) == 'get') { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, 3))); $var = Inflector::lower($uncamelizeMethod); if (isset($this->{$var})) { if (isset($this->thin_type)) { $type = $this->thin_type; Data::getModel($type); $settings = Arrays::exists($type, Data::$_settings) ? Data::$_settings[$type] : []; if (Arrays::exists('relationships', $settings)) { if (Arrays::exists($var, $settings['relationships'])) { return Data::getById($var, $this->{$var}); } } } if (Arrays::is($this->{$var}) && count($argv) == 1) { $o = new self(); $getter = getter(Arrays::first($argv)); $o->populate($this->{$var}); return $o->{$getter}(); } if ($this->{$var} instanceof Closure) { if (is_callable($this->{$var}) && count($argv)) { return call_user_func_array($this->{$var}, $argv); } } return count($argv) && is_null($this->{$var}) ? Arrays::first($argv) : $this->{$var}; } else { if (isset($this->db_instance)) { return $this->db_instance->getValue($this, $var); } if (isset($this->thin_type)) { $type = $this->thin_type; Data::getModel($type); $settings = Arrays::exists($type, Data::$_settings) ? Data::$_settings[$type] : []; $relationships = Arrays::exists('relationships', $settings) ? $settings['relationships'] : []; if (Arrays::exists($var, $relationships) && 's' == $var[strlen($var) - 1]) { if (Arrays::exists($var, $relationships)) { $res = dm(substr($var, 0, -1))->where("{$type} = " . $this->id)->get(); $collection = []; if (count($res)) { foreach ($res as $obj) { array_push($collection, $obj); } } return $collection; } } elseif (Arrays::exists('defaultValues', $settings)) { if (Arrays::is($settings['defaultValues'])) { if (Arrays::exists($this->{$var}, $settings['defaultValues'])) { return $settings['defaultValues'][$this->{$var}]; } } } } if (count($argv) == 1) { return Arrays::first($argv); } return null; } } elseif (substr($func, 0, 3) == 'has') { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, 3))); $var = Inflector::lower($uncamelizeMethod); if (isset($this->{$var})) { return !empty($this->{$var}); } elseif (isset($this->db_instance)) { return $this->db_instance->hasValue($this, $var); } } elseif (substr($func, 0, 3) == 'set') { $value = Arrays::first($argv); $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, 3))); $var = Inflector::lower($uncamelizeMethod); if (!empty($var)) { if (isset($this->thin_type)) { Data::getModel($this->thin_type); $fields = Arrays::exists($this->thin_type, Data::$_fields) ? Data::$_fields[$this->thin_type] : []; if (!Arrays::exists($var, $fields)) { throw new Exception($var . ' is not defined in the model => ' . $this->thin_type); } else { $settingsField = $fields[$var]; if (Arrays::exists('checkValue', $settingsField)) { $functionCheck = $settingsField['checkValue']; $value = $functionCheck($value); } if (is_object($value)) { if (isset($value->thin_type)) { if ($value->thin_type == $var) { $value = $value->id; } } } } } $this->{$var} = $value; if (!Arrays::in($var, $this->_fields)) { $this->_fields[] = $var; } if (isset($this->is_thin_object)) { $name = $this->is_thin_object; $objects = Utils::get('thinObjects'); $this->values = null; $objects[$name] = $this; Utils::set('thinObjects', $objects); } if (isset($this->is_app)) { if (true === $this->is_app) { Utils::set('ThinAppContainer', $this); } } } elseif (isset($this->db_instance)) { return $this->db_instance->setValue($this, $var, $value); } return $this; } elseif (substr($func, 0, 3) == 'add') { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, 3))); $var = Inflector::lower($uncamelizeMethod) . 's'; $value = Arrays::first($argv); if (!isset($this->{$var})) { $this->{$var} = []; } if (!Arrays::is($this->{$var})) { $this->{$var} = []; } array_push($this->{$var}, $value); return $this; } elseif (substr($func, 0, 6) == 'remove') { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, 6))); $var = Inflector::lower($uncamelizeMethod) . 's'; $value = Arrays::first($argv); if (isset($this->{$var})) { if (Arrays::is($this->{$var})) { if (count($this->{$var})) { $remove = false; foreach ($this->{$var} as $key => $tmpValue) { $comp = md5(serialize($value)) == md5(serialize($tmpValue)); if (true === $comp) { $remove = true; break; } } if (true === $remove) { unset($this->{$var}[$key]); } } } } return $this; } if (Arrays::in($func, $this->_fields)) { if ($this->{$func} instanceof Closure) { return call_user_func_array($this->{$func}, $argv); } } if (Arrays::exists($func, $this->_closures)) { if ($this->_closures[$func] instanceof Closure) { return call_user_func_array($this->_closures[$func], $argv); } } if (isset($this->_token)) { $id = sha1($func . $this->_token); if (Arrays::is($this->values)) { if (Arrays::exists($id, $this->values)) { return call_user_func_array($this->values[$id], $argv); } } } if (true === hasEvent($func)) { array_push($argv, $this); return fire($func, $argv); } if (!is_callable($func) || substr($func, 0, 6) !== 'array_' || substr($func, 0, 3) !== 'set' || substr($func, 0, 3) !== 'get' || substr($func, 0, 3) !== 'has' || substr($func, 0, 3) !== 'add' || substr($func, 0, 6) !== 'remove') { $callable = strrev(repl('_', '', $func)); if (!is_callable($callable)) { if (method_exists($this, $callable)) { return call_user_func_array(array($this, $callable), $argv); } } else { return call_user_func_array($callable, $argv); } if (isset($this->thin_litedb)) { $closure = isAke($this->thin_litedb->closures, $func); if (!empty($closure) && $closure instanceof Closure) { return $closure($this); } } if (isset($this->db_instance)) { return $this->db_instance->{$func}($this, $var, $value); call_user_func_array(array($this->db_instance, $func), array_merge(array($this), $argv)); } if (false !== $orm) { $db = call_user_func_array($orm, []); $fields = array_keys($db->map['fields']); if (Arrays::in($func, $fields)) { if (!count($argv)) { return $this->{$func}; } else { $setter = setter($func); $this->{$setter}(Arrays::first($argv)); return $this; } } $tab = str_split($func); $many = false; if (Arrays::last($tab) == 's') { array_pop($tab); $table = implode('', $tab); $many = true; } else { $table = $func; } $object = count($argv) == 1 ? Arrays::first($argv) : false; $model = model($table); return true === $many ? $model->where($db->table . '_id = ' . $this->id)->exec($object) : $model->where($db->table . '_id = ' . $this->id)->first($object); } if (false !== $dbjson) { $db = $this->model()->db(); $fields = $db->fields(); $modelMethods = get_class_methods('Dbjson\\Model'); if (Arrays::in($func, $fields)) { if (!count($argv)) { return $this->{$func}; } else { $setter = setter($func); $this->{$setter}(Arrays::first($argv)); return $this; } } if (Arrays::in($func, $modelMethods)) { return call_user_func_array([$this->model(), $func], $argv); } $tab = str_split($func); $many = false; if (Arrays::last($tab) == 's') { array_pop($tab); $table = implode('', $tab); $many = true; } else { $table = $func; } $object = count($argv) == 1 ? Arrays::first($argv) : true; $model = jdb($db->db, $table); return true === $many ? $model->where($db->table . '_id = ' . $this->id)->exec($object) : $model->where($db->table . '_id = ' . $this->id)->first($object); } return null; } return call_user_func_array($func, array_merge(array($this->getArrayCopy()), $argv)); }
private function globIds() { $storage = Config::get($this->db . '.storage', 'local'); if (true === $this->cacheEnabled) { $data = 'dbJSon::globids::data::' . $this->db . '_' . $this->getEnv() . '::' . $this->table; $ageKey = 'dbJSon::globids::age::' . $this->db . '_' . $this->getEnv() . '::' . $this->table; $ageGlob = $this->cache()->get($ageKey); $ageGlob = strlen($ageGlob) > 0 ? $ageGlob : 0; $ageAll = $this->cache()->get(sha1($this->dir)); if ($ageGlob < $ageAll || !strlen($ageAll)) { $class = '\\' . __NAMESPACE__ . '\\' . ucfirst(Inflector::lower($storage)); $instance = $class::instance($this); $rows = $instance->globids(); $this->cache()->set($data, serialize($rows)); $this->cache()->set($ageKey, time()); return $rows; } else { return unserialize($this->cache()->get($data)); } } else { $class = '\\' . __NAMESPACE__ . '\\' . ucfirst(Inflector::lower($storage)); $instance = $class::instance($this); $rows = $instance->globids(); return $rows; } }
public function where($key, $operator = null, $value = null) { $this->query[] = func_get_args(); if (func_num_args() == 1) { if (is_array($key)) { if (count($key) == 1) { $operator = '='; $value = array_values($key); $key = array_keys($key); } elseif (count($key) == 3) { list($key, $operator, $value) = $key; } $operator = strtolower($operator); } } if (func_num_args() == 2) { list($value, $operator) = [$operator, '=']; } $collection = coll($this->select($key)); $keyCache = sha1(serialize($this->query) . $this->dir); $ids = fmr('blizzcursor')->aged($keyCache, function () use($collection, $key, $operator, $value) { $results = $collection->filter(function ($item) use($key, $operator, $value) { $item = (object) $item; $actual = isset($item->{$key}) ? $item->{$key} : null; $insensitive = in_array($operator, ['=i', 'like i', 'not like i']); if ((!is_array($actual) || !is_object($actual)) && $insensitive) { $actual = Inflector::lower(Inflector::unaccent($actual)); } if ((!is_array($value) || !is_object($value)) && $insensitive) { $value = Inflector::lower(Inflector::unaccent($value)); } if ($insensitive) { $operator = str_replace(['=i', 'like i'], ['=', 'like'], $operator); } if ($key == 'id' || fnmatch('*_id', $key) && is_numeric($actual)) { $actual = (int) $actual; } switch ($operator) { case '<>': case '!=': return sha1(serialize($actual)) != sha1(serialize($value)); case '>': return $actual > $value; case '<': return $actual < $value; case '>=': return $actual >= $value; case '<=': return $actual <= $value; case 'between': return $actual >= $value[0] && $actual <= $value[1]; case 'not between': return $actual < $value[0] || $actual > $value[1]; case 'in': return in_array($actual, $value); case 'not in': return !in_array($actual, $value); case 'like': $value = str_replace("'", '', $value); $value = str_replace('%', '*', $value); return fnmatch($value, $actual); case 'not like': $value = str_replace("'", '', $value); $value = str_replace('%', '*', $value); $check = fnmatch($value, $actual); return !$check; case 'is': return is_null($actual); case 'is not': return !is_null($actual); case '=': default: return sha1(serialize($actual)) == sha1(serialize($value)); } }); return array_values($results->fetch('id')->toArray()); }, $this->age); $this->resource = lib('array')->makeResource($ids); $this->count = count($this->getIterator()); return $this; }
public function can($permission) { if ($permission instanceof Container) { $permission = $permission->getName(); } if (count($this->userPermissions)) { foreach ($this->userPermissions as $userPermissions) { if ($userPermissions instanceof Collection) { foreach ($userPermissions->rows() as $userPermission) { $tmpPermissions = $userPermission->permission(); if (is_null($tmpPermissions)) { return false; } if ($userPermission->permission()->getName() == Inflector::lower($permission)) { return true; } } } } } return false; }
public function pivot($model) { if ($model instanceof Db) { $model = $model->model(); } $mTable = $model->db()->table; $names = [$this->_db->table, $mTable]; asort($names); $pivot = Inflector::lower('pivot' . implode('', $names)); return Db::instance($this->_db->db, $pivot); }
public function __call($m, $a) { $c = Now::get(str_replace(DS, '.', $this->_db->dir) . '.' . $m); if ($c && is_callable($c)) { $a[] = $this; return call_user_func_array($c, $a); } else { if (fnmatch('set*', $m)) { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, strlen('set')))); $field = Inflector::lower($uncamelizeMethod); if (!empty($a)) { $val = current($a); } else { $val = null; } $this->{$field} = $val; return $this; } elseif (fnmatch('get*', $m)) { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, strlen('set')))); $field = Inflector::lower($uncamelizeMethod); $default = count($a) == 1 ? current($a) : null; return isset($this->{$field}) ? $this->{$field} : $default; } else { return call_user_func_array([$this->_db], $a); } } }
public function model($data = []) { $db = $this->db; $table = $this->table; $modelFile = APPLICATION_PATH . DS . 'models' . DS . 'Way' . DS . 'models' . DS . Inflector::lower($db) . DS . ucfirst(Inflector::lower($table)) . '.php'; if (!is_dir(APPLICATION_PATH . DS . 'models' . DS . 'Way')) { File::mkdir(APPLICATION_PATH . DS . 'models' . DS . 'Way'); } if (!is_dir(APPLICATION_PATH . DS . 'models' . DS . 'Way' . DS . 'models')) { File::mkdir(APPLICATION_PATH . DS . 'models' . DS . 'Way' . DS . 'models'); } if (!is_dir(APPLICATION_PATH . DS . 'models' . DS . 'Way' . DS . 'models' . DS . Inflector::lower($db))) { File::mkdir(APPLICATION_PATH . DS . 'models' . DS . 'Way' . DS . 'models' . DS . Inflector::lower($db)); } if (!File::exists($modelFile)) { File::put($modelFile, str_replace('##class##', ucfirst(Inflector::lower($db)) . ucfirst(Inflector::lower($table)) . 'WayModel', File::read(__DIR__ . DS . 'dbModel.tpl'))); } $class = '\\Thin\\' . ucfirst(Inflector::lower($db)) . ucfirst(Inflector::lower($table)) . 'WayModel'; if (!class_exists($class)) { require_once $modelFile; } $model = $this; return new $class($model, $data); }
/** * @param string $c Type of database factory to create (Mysql, Sqlite,...) * @param PDO $dbHandler */ public static function create($c, $dbHandler = null) { $c = ucfirst(Inflector::lower($c)); if (!TypeAdapter::isValid($c)) { throw new Exception("Database type support for ({$c}) not yet available"); } $method = __NAMESPACE__ . "\\" . "TypeAdapter" . $c; return new $method($dbHandler); }
private function upload($field) { $bucket = container()->bucket(); if (Arrays::exists($field, $_FILES)) { $fileupload = $_FILES[$field]['tmp_name']; $fileuploadName = $_FILES[$field]['name']; if (strlen($fileuploadName)) { $tab = explode(".", $fileuploadName); $data = fgc($fileupload); if (!strlen($data)) { return null; } $ext = Inflector::lower(Arrays::last($tab)); $res = $bucket->data($data, $ext); return $res; } } return null; }
private function compare($comp, $op, $value) { if (isset($comp)) { $comp = Inflector::lower($comp); $value = Inflector::lower($value); switch ($op) { case '=': return sha1($comp) == sha1($value); break; case '>=': return $comp >= $value; break; case '>': return $comp > $value; break; case '<': return $comp < $value; break; case '<=': return $comp <= $value; break; case '<>': case '!=': return sha1($comp) != sha1($value); break; case 'LIKE': $value = repl("'", '', $value); $value = repl('%', '', $value); if (strstr($comp, $value)) { return true; } break; case 'NOTLIKE': $value = repl("'", '', $value); $value = repl('%', '', $value); if (!strstr($comp, $value)) { return true; } break; case 'LIKESTART': $value = repl("'", '', $value); $value = repl('%', '', $value); return substr($comp, 0, strlen($value)) === $value; break; case 'LIKEEND': $value = repl("'", '', $value); $value = repl('%', '', $value); if (!strlen($comp)) { return true; } return substr($comp, -strlen($value)) === $value; break; case 'IN': $value = repl('(', '', $value); $value = repl(')', '', $value); $tabValues = explode(',', $value); return Arrays::in($comp, $tabValues); break; case 'NOTIN': $value = repl('(', '', $value); $value = repl(')', '', $value); $tabValues = explode(',', $value); return !Arrays::in($comp, $tabValues); break; } } return false; }
private function map() { $q = "SHOW COLUMNS FROM {$this->table}"; $res = $this->query($q, false); if (empty($res)) { throw new Exception("The system cannot access to the table {$this->table} on {$this->db}."); } $conf = $pks = $keys = []; foreach ($res as $data) { $field = $data['Field']; $conf[$field] = []; $conf[$field]['type'] = typeSql($data['Type']); $conf[$field]['nullable'] = 'yes' == Inflector::lower($data['Null']) ? true : false; if ($data['Key'] == 'PRI') { array_push($pks, $field); } if (strlen($data['Key']) && $data['Key'] != 'PRI') { array_push($keys, $field); } } $this->pks = $pks; $this->keys = $keys; $this->fields = $conf; }
/** * Determine the intermediate table name for a given model. * * By default, the intermediate table name is the plural names of the models * arranged alphabetically and concatenated with an underscore. * * @param string $model * @return string */ private function intermediate_table($model) { $models = array(Str::plural(static::model_name($model)), Str::plural(static::model_name($this))); sort($models); return Inflector::lower($models[0] . '_' . $models[1]); }
private function parseQuery($query) { $groupBy = array(); $orderBy = array(); $orderDir = array(); $wheres = array(); $limit = 0; $offset = 0; $query = preg_replace('/\\s+/u', ' ', $query); $query = preg_replace('/[\\)`\\s]from[\\(`\\s]/ui', ' FROM ', $query); if (preg_match('/(limit([0-9\\s\\,]+)){1}$/ui', $query, $matches)) { $query = str_ireplace(Arrays::first($matches), '', $query); $tmp = explode(',', $matches[2]); if (isset($tmp[1])) { $offset = (int) trim(Arrays::first($tmp)); $limit = (int) trim($tmp[1]); } else { $offset = 0; $limit = (int) trim(Arrays::first($tmp)); } } if (preg_match('/(order\\sby([^\\(\\)]+)){1}$/ui', $query, $matches)) { $query = str_ireplace(Arrays::first($matches), '', $query); $tmp = explode(',', $matches[2]); foreach ($tmp as $item) { $item = trim($item); $direct = mb_strripos($item, ' desc') == mb_strlen($item) - 5 || mb_strripos($item, '`desc') == mb_strlen($item) - 5 ? 'desc' : 'asc'; $item = str_ireplace(array(' asc', ' desc', '`asc', '`desc', '`'), '', $item); $orderBy[] = $item; $orderDir[] = Inflector::upper($direct); } } if (preg_match('/(group\\sby([^\\(\\)]+)){1}$/ui', $query, $matches)) { $query = str_ireplace(Arrays::first($matches), '', $query); $tmp = explode(',', $matches[2]); foreach ($tmp as $item) { $item = trim($item); $groupBy[] = $item; } } $tmp = preg_replace_callback('/\\( (?> [^)(]+ | (?R) )+ \\)/xui', array($this, 'queryParamsCallback'), $query); $words = explode(' ', $query); $method = Inflector::lower(Arrays::first($words)); $parts = explode(' where ', Inflector::lower($query)); if (2 == count($parts)) { $whs = Arrays::last($parts); $whs = str_replace(array(' and ', ' or ', ' xor ', ' && ', ' || ', ' | '), array(' AND ', ' OR ', ' XOR ', ' AND ', ' OR ', ' XOR '), $whs); $wheres['AND'] = strstr($whs, ' AND ') ? explode(' AND ', $whs) : array(); $wheres['OR'] = strstr($whs, ' OR ') ? explode(' OR ', $whs) : array(); $wheres['XOR'] = strstr($whs, ' XOR ') ? explode(' XOR ', $whs) : array(); } return array('method' => $method, 'wheres' => $wheres, 'groupBy' => $groupBy, 'orderBy' => $orderBy, 'orderDir' => $orderDir, 'limit' => $limit, 'offset' => $offset); }
function lcfirst($str) { $str[0] = Inflector::lower($str[0]); return (string) $str; }