Example #1
0
 private static function eagerly($mongo, &$parents, $include)
 {
     $first = reset($parents);
     $mongo->attributes = $first->attributes;
     $relationship = $mongo->{$include}();
     $mongo->attributes = $_ids = array();
     foreach ($parents as &$parent) {
         $_ids[] = $parent->_id;
         $parent->ignore[$include] = Arrays::in($mongo->relating, array('has_many', 'has_and_belongs_to_many')) ? array() : null;
     }
     if (Arrays::in($relating = $mongo->relating, array('has_one', 'has_many', 'belongs_to'))) {
         static::$relating($relationship, $parents, $mongo->relating_key, $include, $_ids);
     } else {
         static::manyToMany($relationship, $parents, $mongo->relating_key, $mongo->relating_table, $include, $_ids);
     }
 }
Example #2
0
 public function prepare($text)
 {
     $slugs = explode(' ', Inflector::slug($text, ' '));
     if (count($slugs)) {
         $collection = array();
         foreach ($slugs as $slug) {
             if (strlen($slug) > 1) {
                 if (!Arrays::in($slug, $collection)) {
                     array_push($collection, $slug);
                 }
             }
         }
         asort($collection);
     }
     return $collection;
 }
Example #3
0
 public function init()
 {
     $this->view->config = context('config')->load('crudjson');
     $guestActions = array('login', 'logout', 'lost');
     $guestActions += arrayGet($this->view->config, 'guest.actions', array());
     $this->view->isAuth = false;
     $this->view->items = isAke($this->view->config, 'tables');
     $user = auth()->user();
     if (!$user) {
         if (!Arrays::in($this->action(), $guestActions)) {
             $this->forward('login');
         }
     } else {
         $this->view->isAuth = true;
         $this->view->user = $user;
         $this->isAdmin = auth()->is('admin');
         if ($this->action() == 'login' || $this->action() == 'lost') {
             $this->forward('home', 'static');
         }
     }
 }
Example #4
0
 /**
  * Eagerly load a relationship.
  *
  * @param  object  $eloquent
  * @param  array   $parents
  * @param  string  $include
  * @return void
  */
 private static function eagerly($eloquent, &$parents, $include)
 {
     // We temporarily spoof the query attributes to allow the query to be fetched without
     // any problems, since the belongs_to method actually gets the related attribute.
     $first = reset($parents);
     $eloquent->attributes = $first->attributes;
     $relationship = $eloquent->{$include}();
     $eloquent->attributes = array();
     // Reset the WHERE clause and bindings on the query. We'll add our own WHERE clause soon.
     // This will allow us to load a range of related models instead of only one.
     $relationship->query->reset_where();
     // Initialize the relationship attribute on the parents. As expected, "many" relationships
     // are initialized to an array and "one" relationships are initialized to null.
     foreach ($parents as &$parent) {
         $parent->ignore[$include] = Arrays::in($eloquent->relating, array('has_many', 'has_and_belongs_to_many')) ? array() : null;
     }
     if (Arrays::in($relating = $eloquent->relating, array('has_one', 'has_many', 'belongs_to'))) {
         return static::$relating($relationship, $parents, $eloquent->relating_key, $include);
     } else {
         static::has_and_belongs_to_many($relationship, $parents, $eloquent->relating_key, $eloquent->relating_table, $include);
     }
 }
Example #5
0
 public static function dispatch()
 {
     static::$method = Request::method();
     $uri = substr(str_replace('/ws/', '/', $_SERVER['REQUEST_URI']), 1);
     $tab = explode('/', $uri);
     if (count($tab) < 3) {
         Api::forbidden();
     }
     $namespace = current($tab);
     $controller = $tab[1];
     $action = $tab[2];
     $tab = array_slice($tab, 3);
     $count = count($tab);
     if (0 < $count && $count % 2 == 0) {
         for ($i = 0; $i < $count; $i += 2) {
             $_REQUEST[$tab[$i]] = $tab[$i + 1];
         }
     }
     $file = APPLICATION_PATH . DS . 'webservices' . DS . $namespace . DS . $controller . '.php';
     if (!File::exists($file)) {
         Api::NotFound();
     }
     require_once $file;
     $class = 'Thin\\' . ucfirst($controller) . 'Ws';
     $i = new $class();
     $methods = get_class_methods($i);
     $call = strtolower(static::$method) . ucfirst($action);
     if (!Arrays::in($call, $methods)) {
         Api::NotFound();
     }
     if (Arrays::in('init', $methods)) {
         $i->init($call);
     }
     $i->{$call}();
     if (Arrays::in('after', $methods)) {
         $i->after();
     }
 }
Example #6
0
 public function __call($method, $args)
 {
     if (count($this->_items)) {
         $first = $this->first();
         $db = $first->db();
         $methods = get_class_methods($db);
         if (Arrays::in($method, $methods)) {
             $instance = $db->where(['id', 'IN', implode(',', $this->indexes())]);
             return call_user_func_array([$instance, $method], $args);
         }
     }
 }
Example #7
0
 public function fetch($results = null)
 {
     $this->count = count($results);
     $results = empty($results) ? $this->results : $results;
     if (count($results)) {
         if (null !== $this->groupBy) {
             $groupBys = array();
             $ever = array();
             foreach ($results as $key => $object) {
                 $id = $object->getId();
                 $getter = getter($this->groupBy);
                 $obj = $object->{$getter}();
                 if ($obj instanceof Container) {
                     $id = $obj->getId();
                 }
                 if (!Arrays::in($id, $ever)) {
                     $groupBys[$key] = $this->find($id);
                     $ever[] = $id;
                 }
             }
             $this->results = $groupBys;
             $this->order($this->groupBy);
             $results = $this->results;
         }
         if (0 < $this->limit) {
             $max = count($results);
             $number = $this->limit - $this->offset;
             if ($number > $max) {
                 $this->offset = $max - $this->limit;
                 if (0 > $this->offset) {
                     $this->offset = 0;
                 }
                 $this->limit = $max;
             }
             $results = array_slice($results, $this->offset, $this->limit);
         }
     }
     $this->results = $results;
     return $results;
 }
Example #8
0
 /**
  * @param  $key
  * @return mixed
  */
 public function __get($key)
 {
     if (Arrays::exists($key, $this->attributes)) {
         return $this->attributes[$key];
     } elseif (Arrays::exists($key, $this->ignore)) {
         return $this->ignore[$key];
     } elseif (method_exists($this, $key)) {
         $query = $this->{$key}();
         return $this->ignore[$key] = Arrays::in($this->relating, array('one', 'oneToOne')) ? $query->first() : $query->get();
     }
 }
Example #9
0
 private function compare($comp, $op, $value)
 {
     $keyCache = sha1('compare_' . serialize(func_get_args()));
     $cached = $this->cached($keyCache);
     if (empty($cached)) {
         $res = false;
         if (isset($comp)) {
             $comp = Inflector::lower($comp);
             $value = Inflector::lower($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 = repl("'", '', $value);
                     $value = repl('%', '', $value);
                     if (strstr($comp, $value)) {
                         $res = true;
                     }
                     break;
                 case 'NOTLIKE':
                     $value = repl("'", '', $value);
                     $value = repl('%', '', $value);
                     if (!strstr($comp, $value)) {
                         $res = true;
                     }
                     break;
                 case 'LIKE START':
                     $value = repl("'", '', $value);
                     $value = repl('%', '', $value);
                     $res = substr($comp, 0, strlen($value)) === $value;
                     break;
                 case 'LIKE END':
                     $value = repl("'", '', $value);
                     $value = repl('%', '', $value);
                     if (!strlen($comp)) {
                         $res = true;
                     }
                     $res = substr($comp, -strlen($value)) === $value;
                     break;
                 case 'IN':
                     $value = repl('(', '', $value);
                     $value = repl(')', '', $value);
                     $tabValues = explode(',', $value);
                     $res = Arrays::in($comp, $tabValues);
                     break;
                 case 'NOTIN':
                     $value = repl('(', '', $value);
                     $value = repl(')', '', $value);
                     $tabValues = explode(',', $value);
                     $res = !Arrays::in($comp, $tabValues);
                     break;
             }
         }
         $this->cached($keyCache, $res);
         return $res;
     }
     return $cached;
 }
Example #10
0
    public static function rowsForm($idField, $table, $fields, $order = null, $valueField = null, $required = true, $default = null, $data = null, $sort = 'ASC', $database = null)
    {
        /* polymorphism */
        $fields = !Arrays::is($fields) ? strstr($fields, ',') ? explode(',', repl(' ', '', $fields)) : [$fields] : $fields;
        if (fnmatch('*:*', $table)) {
            list($database, $table) = explode(':', $table, 2);
        } else {
            $database = is_null($database) ? SITE_NAME : $database;
        }
        $default = null !== request()->{$idField} ? request()->{$idField} : $default;
        if ($default instanceof \Closure) {
            dd('ici');
            $default = $default();
        }
        $defined = !is_null($default) && null !== request()->{$idField};
        $db = Db::instance($database, $table);
        $require = $required ? 'required ' : '';
        $multiple = $idField == request()->is_multiple ? 'multiple ' : '';
        $class = strlen($multiple) ? 'multi-select' : 'form-control';
        $inputName = strlen($multiple) ? $idField . '[]' : $idField;
        $html = '<span id="span_' . $idField . '"><select ' . $multiple . $require . 'class="' . $class . '" name="' . $inputName . '" id="' . $idField . '">' . NL;
        if (false === $defined && !strlen($multiple)) {
            $html .= '<option value="">Choisir</option>' . NL;
        }
        $order = is_null($order) ? 'id' : $order;
        $data = is_null($data) ? $db->where(['id', '>', 0])->order($order, $sort)->exec() : $data();
        if (count($data)) {
            foreach ($data as $target) {
                $value = [];
                $id = $target['id'];
                foreach ($fields as $field) {
                    if (!$field instanceof Closure) {
                        $value[] = isAke($target, $field, $field);
                    } else {
                        $value[] = $field($target);
                    }
                }
                $value = implode(' ', $value);
                if (strstr($_SERVER['REQUEST_URI'], '/create/')) {
                    $valueField = empty($valueField) ? $default : $valueField;
                }
                if (!Arrays::is($valueField)) {
                    $selected = $valueField == $id ? 'selected ' : '';
                } else {
                    $selected = Arrays::in($id, $valueField) ? 'selected ' : '';
                }
                if (false === $defined) {
                    $html .= '<option ' . $selected . 'value="' . $id . '">' . \Thin\Html\Helper::display($value) . '</option>' . NL;
                } else {
                    if (!strlen($selected)) {
                        $html .= '<option disabled value="' . $id . '">' . \Thin\Html\Helper::display($value) . '</option>' . NL;
                    } else {
                        $html .= '<option selected value="' . $id . '">' . \Thin\Html\Helper::display($value) . '</option>' . NL;
                    }
                }
            }
        }
        $html .= '</select></span>';
        if (strlen($multiple)) {
            $css = '<style> .ms-container{
  background: transparent url(\'/crud/assets/img/switch.png\') no-repeat 50% 50%;
  width: 100%;
}

.ms-container:after{
  content: ".";
  display: block;
  height: 0;
  line-height: 0;
  font-size: 0;
  clear: both;
  min-height: 0;
  visibility: hidden;
}

.ms-container .ms-selectable, .ms-container .ms-selection{
  background: #fff;
  color: #555555;
  float: left;
  width: 45%;
  font-size: 10px;
}
.ms-container .ms-selection{
  float: right;
}

.ms-container .ms-list{
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  -webkit-transition: border linear 0.2s, box-shadow linear 0.2s;
  -moz-transition: border linear 0.2s, box-shadow linear 0.2s;
  -ms-transition: border linear 0.2s, box-shadow linear 0.2s;
  -o-transition: border linear 0.2s, box-shadow linear 0.2s;
  transition: border linear 0.2s, box-shadow linear 0.2s;
  border: 1px solid #ccc;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  position: relative;
  height: 200px;
  padding: 0;
  overflow-y: auto;
}

.ms-container .ms-list.ms-focus{
  border-color: rgba(82, 168, 236, 0.8);
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
  -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
  outline: 0;
  outline: thin dotted \\9;
}

.ms-container ul{
  margin: 0;
  list-style-type: none;
  padding: 0;
}

.ms-container .ms-optgroup-container {
  width: 100%;
}

.ms-container .ms-optgroup-label {
  margin: 0;
  padding: 5px 0px 0px 5px;
  cursor: pointer;
  color: #999;
}

.ms-container .ms-selectable li.ms-elem-selectable,
.ms-container .ms-selection li.ms-elem-selection {
  border-bottom: 1px #eee solid;
  padding: 2px 10px;
  color: #555;
  font-size: 10px;
}

.ms-container .ms-selectable li.ms-hover,
.ms-container .ms-selection li.ms-hover {
  cursor: pointer;
  color: #fff;
  text-decoration: none;
  background-color: #08c;
}

.ms-container .ms-selectable li.disabled,
.ms-container .ms-selection li.disabled {
  background-color: #eee;
  color: #aaa;
  cursor: text;
}</style>';
            $js = "<script>\$('#{$idField}').multiSelect();</script>";
            $html .= $css . $js;
        }
        return $html;
    }
Example #11
0
 public function row($tab = array())
 {
     $fields = array_keys($this->map['fields']);
     $pk = $this->pk();
     $id = isAke($tab, $pk, false);
     if (count($tab)) {
         foreach ($tab as $key => $value) {
             if (!Arrays::in($key, $fields)) {
                 unset($tab[$key]);
             }
         }
         foreach ($fields as $field) {
             $val = isAke($tab, $field, false);
             if (false === $val && false === $id) {
                 $tab[$field] = null;
             }
         }
     } else {
         foreach ($fields as $field) {
             if (false === $id) {
                 $tab[$field] = null;
             }
         }
     }
     $o = new Container();
     $o->populate($tab);
     return $this->closures($o);
 }
Example #12
0
 public function __call($func, $args)
 {
     if (substr($func, 0, strlen('get')) == 'get') {
         $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, strlen('get'))));
         $field = Inflector::lower($uncamelizeMethod);
         $default = count($args) == 1 ? Arrays::first($args) : null;
         $res = isAke($this->_data, $field, false);
         if (false !== $res) {
             return $res;
         } else {
             $resFk = isAke($this->_data, $field . '_id', false);
             if (false !== $resFk) {
                 $db = Db::instance($this->_db->db, $field);
                 $object = count($args) == 1 ? $args[0] : false;
                 if (!is_bool($object)) {
                     $object = false;
                 }
                 return $db->find($resFk, $object);
             } else {
                 if ($field[strlen($field) - 1] == 's' && isset($this->_data['id']) && $field[0] != '_') {
                     $db = Db::instance($this->_db->db, substr($field, 0, -1));
                     $object = count($args) == 1 ? $args[0] : false;
                     if (!is_bool($object)) {
                         $object = false;
                     }
                     $hasPivot = $this->hasPivot($db);
                     if (true === $hasPivot) {
                         $model = $db->model();
                         $pivots = $this->pivots($model)->exec();
                         $ids = [];
                         if (!empty($pivots)) {
                             foreach ($pivots as $pivot) {
                                 $id = isAke($pivot, substr($field, 0, -1) . '_id', false);
                                 if (false !== $id) {
                                     array_push($ids, $id);
                                 }
                             }
                             if (!empty($ids)) {
                                 return $db->where(['id', 'IN', implode(',', $ids)])->exec($object);
                             } else {
                                 return [];
                             }
                         }
                     } else {
                         $idField = $this->_db->table . '_id';
                         return $db->where([$idField, '=', $this->_data['id']])->exec($object);
                     }
                 } else {
                     return $default;
                 }
             }
         }
     } elseif (substr($func, 0, strlen('has')) == 'has') {
         $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, strlen('has'))));
         $field = Inflector::lower($uncamelizeMethod);
         $res = isAke($this->_data, $field, false);
         if (false !== $res) {
             return true;
         } else {
             $resFk = isAke($this->_data, $field . '_id', false);
             if (false !== $resFk) {
                 return true;
             } else {
                 if ($field[strlen($field) - 1] == 's' && isset($this->_data['id']) && $field[0] != '_') {
                     $db = Db::instance($this->_db->db, substr($field, 0, -1));
                     $hasPivot = $this->hasPivot($db);
                     if (true === $hasPivot) {
                         $model = $db->model();
                         $pivots = $this->pivots($model)->exec();
                         $ids = [];
                         if (!empty($pivots)) {
                             foreach ($pivots as $pivot) {
                                 $id = isAke($pivot, substr($field, 0, -1) . '_id', false);
                                 if (false !== $id) {
                                     array_push($ids, $id);
                                 }
                             }
                             return !empty($ids) ? true : false;
                         }
                     } else {
                         $idField = $this->_db->table . '_id';
                         $count = $db->where([$idField, '=', $this->_data['id']])->count();
                         return $count > 0 ? true : false;
                     }
                 }
             }
         }
         return false;
     } elseif (substr($func, 0, strlen('set')) == 'set') {
         $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, strlen('set'))));
         $field = Inflector::lower($uncamelizeMethod);
         if (!empty($args)) {
             $val = Arrays::first($args);
         } else {
             $val = null;
         }
         if (is_object($val)) {
             $val = (int) $val->id;
         }
         if (fnmatch('*_id', $field)) {
             if (is_numeric($val)) {
                 $val = (int) $val;
             }
         }
         $this->_data[$field] = $val;
         $autosave = isAke($this->_data, 'autosave', false);
         return !$autosave ? $this : $this->save();
     } else {
         $cb = isAke($this->_events, $func, false);
         if (false !== $cb) {
             if ($cb instanceof Closure) {
                 return call_user_func_array($cb, $args);
             }
         } else {
             if ($func[strlen($func) - 1] == 's' && isset($this->_data['id']) && $func[0] != '_') {
                 $db = Db::instance($this->_db->db, substr($func, 0, -1));
                 $object = count($args) == 1 ? $args[0] : false;
                 if (!is_bool($object)) {
                     $object = false;
                 }
                 $hasPivot = $this->hasPivot($db);
                 if (true === $hasPivot) {
                     $model = $db->model();
                     $pivots = $this->pivots($model)->exec();
                     $ids = [];
                     if (!empty($pivots)) {
                         foreach ($pivots as $pivot) {
                             $id = isAke($pivot, substr($func, 0, -1) . '_id', false);
                             if (false !== $id) {
                                 array_push($ids, $id);
                             }
                         }
                         if (!empty($ids)) {
                             return $db->where(['id', 'IN', implode(',', $ids)])->exec($object);
                         } else {
                             return [];
                         }
                     }
                 } else {
                     $idField = $this->_db->table . '_id';
                     return $db->where([$idField, '=', $this->_data['id']])->exec($object);
                 }
             } else {
                 if (count($args)) {
                     $object = count($args) == 1 ? $args[0] : false;
                     $db = Db::instance($this->_db->db, $func);
                     $field = $func . '_id';
                     if (is_bool($object) && isset($this->_data[$field])) {
                         return $db->find($value, $object);
                     } elseif (is_object($object)) {
                         $this->{$field} = (int) $object->id;
                         return $this;
                     }
                 }
                 $auth = ['_hooks'];
                 if (Arrays::in($func, $auth)) {
                     return true;
                 }
                 throw new Exception("{$func} is not a model function of {$this->_db}.");
             }
         }
     }
 }
Example #13
0
 function in_arrayi($needle, $haystack)
 {
     return Arrays::in(Inflector::lower($needle), array_map('strtolower', $haystack));
 }
Example #14
0
 /**
  * Magic Method for handling dynamic method calls.
  */
 public function __call($method, $parameters)
 {
     // To allow the "with", "get", "first", and "paginate" methods to be called both
     // staticly and on an instance, we need to have private, underscored versions
     // of the methods and handle them dynamically.
     if (Arrays::in($method, array('with', 'get', 'first', 'paginate'))) {
         return call_user_func_array(array($this, '_' . $method), $parameters);
     }
     // All of the aggregate and persistance functions can be passed directly to the query
     // instance. For these functions, we can simply return the response of the query.
     if (Arrays::in($method, array('insert', 'update', 'increment', 'decrement', 'abs', 'count', 'sum', 'min', 'max', 'avg'))) {
         return call_user_func_array(array($this->query, $method), $parameters);
     }
     // Pass the method to the query instance. This allows the chaining of methods
     // from the query builder, providing the same convenient query API as the
     // query builder itself.
     call_user_func_array(array($this->query, $method), $parameters);
     return $this;
 }
Example #15
0
 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;
 }
Example #16
0
 /**
  * Determine if the error type is fatal.
  *
  * @param  int  $type
  * @return bool
  */
 protected function isFatal($type)
 {
     return Arrays::in($type, [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE]);
 }
Example #17
0
 /**
  * @param string $c
  * @return boolean
  */
 public static function isValid($c)
 {
     return Arrays::in($c, self::$enums);
 }
Example #18
0
 public function join($model, $fieldJoin = null)
 {
     $fields = $this->fields();
     $fieldJoin = is_null($fieldJoin) ? $model . '_id' : $fieldJoin;
     if (!Arrays::in($fieldJoin, $fields)) {
         throw new Exception("'{$fieldJoin}' unknown in {$this->table} model. This join is not possible.");
     }
     $this->joinTable[$model] = $fieldJoin;
     return $this;
 }
Example #19
0
 public function row(array $data, $recursive = true, $extends = array())
 {
     if (Arrays::isAssoc($data)) {
         $obj = o(sha1(serialize($data)));
         $obj->db_instance = $this;
         if (count($extends)) {
             foreach ($extends as $name => $instance) {
                 $closure = function ($object) use($name, $instance) {
                     $idx = $object->is_thin_object;
                     $objects = Utils::get('thinObjects');
                     return $instance->{$name}($objects[$idx]);
                 };
                 $obj->_closures[$name] = $closure;
             }
         }
         $fields = $this->fields();
         foreach ($fields as $field) {
             $hasFk = $this->hasFk($field);
             if (false === $hasFk) {
                 $obj->{$field} = $data[$field];
             } else {
                 extract($hasFk);
                 $ar = ar($foreignEntity, $foreignTable);
                 $one = contain('toone', Inflector::lower($type));
                 if ($one && $recursive) {
                     $foreignObj = $ar->findBy($foreignKey, $data[$field], $one);
                     $obj->{$relationKey} = $foreignObj;
                 }
             }
         }
         $hasFk = ake('relationships', $this->_settings);
         if (true === $hasFk && $recursive) {
             $rs = $this->_settings['relationships'];
             if (count($rs)) {
                 foreach ($rs as $field => $infos) {
                     extract($infos);
                     $ar = ar($foreignEntity, $foreignTable);
                     if (!Arrays::in($field, $fields)) {
                         $pk = $this->pk();
                         $obj->{$field} = $ar->findBy($foreignKey, $obj->{$pk}, false, false);
                     }
                 }
             }
         }
         return $obj;
     }
     return null;
 }
Example #20
0
 public function groupBy($field, $results = array())
 {
     $res = count($results) ? $results : $this->results;
     $groupBys = array();
     $ever = array();
     foreach ($res as $key => $id) {
         $object = $this->row($id);
         $getter = getter($field);
         $obj = $object->{$getter}();
         if ($obj instanceof Container) {
             $obj = $obj->getId();
         }
         if (!Arrays::in($obj, $ever)) {
             $groupBys[$key] = $id;
             $ever[] = $obj;
         }
     }
     $this->results = $groupBys;
     $this->order($field);
     return $this;
 }
Example #21
0
 public function __call($fn, $args)
 {
     $fields = $this->fields();
     $method = substr($fn, 0, 2);
     $object = lcfirst(substr($fn, 2));
     if ('is' === $method && strlen($fn) > 2) {
         $field = Inflector::uncamelize($object);
         if (!Arrays::in($field, $fields)) {
             $field = $field . '_id';
             $model = Arrays::first($args);
             if ($model instanceof Container) {
                 $idFk = $model->id();
             } else {
                 $idFk = $model;
             }
             return $this->where("{$field} = {$idFk}");
         } else {
             return $this->where($field . ' = ' . Arrays::first($args));
         }
     }
     $method = substr($fn, 0, 4);
     $object = lcfirst(substr($fn, 4));
     if ('orIs' === $method && strlen($fn) > 4) {
         $field = Inflector::uncamelize($object);
         if (!Arrays::in($field, $fields)) {
             $field = $field . '_id';
             $model = Arrays::first($args);
             if ($model instanceof Container) {
                 $idFk = $model->id();
             } else {
                 $idFk = $model;
             }
             return $this->where("{$field} = {$idFk}", 'OR');
         } else {
             return $this->where($field . ' = ' . Arrays::first($args), 'OR');
         }
     } elseif ('like' === $method && strlen($fn) > 4) {
         $field = Inflector::uncamelize($object);
         $op = count($args) == 2 ? Arrays::last($args) : 'AND';
         return $this->like($field, Arrays::first($args), $op);
     }
     $method = substr($fn, 0, 5);
     $object = lcfirst(substr($fn, 5));
     if (strlen($fn) > 5) {
         if ('where' == $method) {
             $field = Inflector::uncamelize($object);
             if (!Arrays::in($field, $fields)) {
                 $field = $field . '_id';
                 $model = Arrays::first($args);
                 if ($model instanceof Container) {
                     $idFk = $model->id();
                 } else {
                     $idFk = $model;
                 }
                 return $this->where("{$field} = {$idFk}");
             } else {
                 return $this->where($field . ' ' . Arrays::first($args));
             }
         } elseif ('xorIs' === $method) {
             $field = Inflector::uncamelize($object);
             if (!Arrays::in($field, $fields)) {
                 $field = $field . '_id';
                 $model = Arrays::first($args);
                 if ($model instanceof Container) {
                     $idFk = $model->id();
                 } else {
                     $idFk = $model;
                 }
                 return $this->where("{$field} = {$idFk}", 'XOR');
             } else {
                 return $this->where($field . ' = ' . Arrays::first($args), 'XOR');
             }
         } elseif ('andIs' === $method) {
             $field = Inflector::uncamelize($object);
             if (!Arrays::in($field, $fields)) {
                 $field = $field . '_id';
                 $model = Arrays::first($args);
                 if ($model instanceof Container) {
                     $idFk = $model->id();
                 } else {
                     $idFk = $model;
                 }
                 return $this->where("{$field} = {$idFk}");
             } else {
                 return $this->where($field . ' = ' . Arrays::first($args));
             }
         }
     }
     $method = substr($fn, 0, 6);
     $object = Inflector::uncamelize(lcfirst(substr($fn, 6)));
     if (strlen($fn) > 6) {
         if ('findBy' == $method) {
             return $this->findBy($object, Arrays::first($args));
         }
     }
     $method = substr($fn, 0, 7);
     $object = lcfirst(substr($fn, 7));
     if (strlen($fn) > 7) {
         if ('orWhere' == $method) {
             $field = Inflector::uncamelize($object);
             if (!Arrays::in($field, $fields)) {
                 $field = $field . '_id';
                 $model = Arrays::first($args);
                 if ($model instanceof Container) {
                     $idFk = $model->id();
                 } else {
                     $idFk = $model;
                 }
                 return $this->where("{$field} = {$idFk}", 'OR');
             } else {
                 return $this->where($field . ' ' . Arrays::first($args), 'OR');
             }
         } elseif ('orderBy' == $method) {
             $object = Inflector::uncamelize(lcfirst(substr($fn, 7)));
             if ($object == 'id') {
                 $object = $this->pk();
             }
             if (!Arrays::in($object, $fields)) {
                 $object = Arrays::in($object . '_id', $fields) ? $object . '_id' : $object;
             }
             $direction = count($args) ? Arrays::first($args) : 'ASC';
             return $this->order($object, $direction);
         } elseif ('groupBy' == $method) {
             $object = Inflector::uncamelize(lcfirst(substr($fn, 7)));
             if ($object == 'id') {
                 $object = $this->pk();
             }
             if (!Arrays::in($object, $fields)) {
                 $object = Arrays::in($object . '_id', $fields) ? $object . '_id' : $object;
             }
             return $this->groupBy($object);
         }
     }
     $method = substr($fn, 0, 9);
     $object = Inflector::uncamelize(lcfirst(substr($fn, 9)));
     if (strlen($fn) > 9) {
         if ('findOneBy' == $method) {
             return $this->findOneBy($object, Arrays::first($args));
         }
     }
     $method = substr($fn, 0, 13);
     $object = Inflector::uncamelize(lcfirst(substr($fn, 13)));
     if (strlen($fn) > 13) {
         if ('findObjectsBy' == $method) {
             return $this->findBy($object, Arrays::first($args), true);
         }
     }
     $method = substr($fn, 0, 15);
     $object = Inflector::uncamelize(lcfirst(substr($fn, 15)));
     if (strlen($fn) > 15) {
         if ('findOneObjectBy' == $method) {
             return $this->findOneBy($object, Arrays::first($args), true);
         }
     }
     $method = substr($fn, 0, 8);
     $object = lcfirst(substr($fn, 8));
     if (strlen($fn) > 8) {
         if ('xorWhere' == $method) {
             $field = Inflector::uncamelize($object);
             if (!Arrays::in($field, $fields)) {
                 $field = $field . '_id';
                 $model = Arrays::first($args);
                 if ($model instanceof Container) {
                     $idFk = $model->id();
                 } else {
                     $idFk = $model;
                 }
                 return $this->where("{$field} = {$idFk}", 'XOR');
             } else {
                 return $this->where($field . ' ' . Arrays::first($args), 'XOR');
             }
         } elseif ('andWhere' == $method) {
             $field = Inflector::uncamelize($object);
             if (!Arrays::in($field, $fields)) {
                 $field = $field . '_id';
                 $model = Arrays::first($args);
                 if ($model instanceof Container) {
                     $idFk = $model->id();
                 } else {
                     $idFk = $model;
                 }
                 return $this->where("{$field} = {$idFk}");
             } else {
                 return $this->where($field . ' ' . Arrays::first($args));
             }
         }
     } else {
         $field = $fn;
         $fieldFk = $fn . '_id';
         $op = count($args) == 2 ? Inflector::upper(Arrays::last($args)) : 'AND';
         if (Arrays::in($field, $fields)) {
             return $this->where($field . ' = ' . Arrays::first($args), $op);
         } else {
             if (Arrays::in($fieldFk, $fields)) {
                 $model = Arrays::first($args);
                 if ($model instanceof Container) {
                     $idFk = $model->id();
                 } else {
                     $idFk = $model;
                 }
                 return $this->where("{$fieldFk} = {$idFk}", $op);
             }
         }
     }
     throw new Exception("Method '{$fn}' is unknown.");
 }
Example #22
0
 public static function dispatch()
 {
     header("Access-Control-Allow-Origin: *");
     static::$method = Request::method();
     $uri = substr(str_replace('/mobi/', '/', $_SERVER['REQUEST_URI']), 1);
     $tab = explode('/', $uri);
     if (!strlen($uri) || $uri == '/') {
         $namespace = 'static';
         $controller = 'home';
         $action = 'index';
     } else {
         if (count($tab) < 3) {
             self::isForbidden();
         }
         $namespace = current($tab);
         $controller = $tab[1];
         $action = $tab[2];
         $tab = array_slice($tab, 3);
         $count = count($tab);
         if (0 < $count && $count % 2 == 0) {
             for ($i = 0; $i < $count; $i += 2) {
                 $_REQUEST[$tab[$i]] = $tab[$i + 1];
             }
         }
     }
     $file = APPLICATION_PATH . DS . 'mobi' . DS . $namespace . DS . 'controllers' . DS . $controller . '.php';
     // dd($file);
     if (!File::exists($file)) {
         self::is404();
     }
     require_once $file;
     $class = 'Thin\\' . ucfirst($controller) . 'Mobi';
     $i = new $class();
     $methods = get_class_methods($i);
     $call = strtolower(static::$method) . ucfirst($action);
     if (!Arrays::in($call, $methods)) {
         self::is404();
     }
     if (Arrays::in('init', $methods)) {
         $i->init($call);
     }
     $i->{$call}();
     if ($i->view === true) {
         $tpl = APPLICATION_PATH . DS . 'mobi' . DS . $namespace . DS . 'views' . DS . $controller . DS . $action . '.phtml';
         if (File::exists($tpl)) {
             $content = File::read($tpl);
             $content = str_replace('$this->', '$i->', $content);
             $fileTpl = CACHE_PATH . DS . sha1($content) . '.display';
             File::put($fileTpl, $content);
             ob_start();
             include $fileTpl;
             $html = ob_get_contents();
             ob_end_clean();
             File::delete($fileTpl);
             self::render($html);
         } else {
             self::render('OK');
         }
     }
     if (Arrays::in('after', $methods)) {
         $i->after();
     }
 }
Example #23
0
 public function fields($keys = true)
 {
     $configFields = isAke($this->config, 'fields', false);
     if (false === $configFields) {
         $row = $this->model->first(false, false);
         if (!empty($row)) {
             unset($row['created_at']);
             unset($row['updated_at']);
             ksort($row);
             return array_keys($row);
         }
         return ['id'];
     } else {
         $ignoreFields = isAke($this->config, 'ignore_fields', false);
         if (false === $ignoreFields) {
             return array_merge(['id'], array_keys($configFields));
         } else {
             $fields = array_merge(['id'], array_keys($configFields));
             $collection = [];
             if (!Arrays::is($ignoreFields)) {
                 return $fields;
             }
             if (!count($ignoreFields)) {
                 return $fields;
             }
             foreach ($fields as $field) {
                 if (!Arrays::in($field, $ignoreFields)) {
                     array_push($collection, $field);
                 }
             }
             return $collection;
         }
     }
 }
Example #24
0
 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();
     }
 }
Example #25
0
 /**
  * Load any plugins
  */
 private function loadPlugins()
 {
     $dir = realpath(APPLICATION_PATH . DS . '..' . DS . 'public' . DS . 'content' . DS . SITE_NAME . DS . 'plugins');
     $this->plugins = array();
     $plugins = $this->getFiles($dir, '.php');
     if (!empty($plugins)) {
         foreach ($plugins as $plugin) {
             $getNamespaceAndClassNameFromCode = getNamespaceAndClassNameFromCode(fgc($plugin));
             list($namespace, $class) = $getNamespaceAndClassNameFromCode;
             require_once $plugin;
             $actions = get_class_methods($namespace . '\\' . $class);
             $nsClass = '\\' . $namespace . '\\' . $class;
             $instance = new $nsClass();
             if (Arrays::in('init', $actions)) {
                 $instance::init();
             }
             array_push($this->plugins, $instance);
             $this->plugins[] = $obj;
         }
     }
 }
Example #26
0
 public static function dispatch()
 {
     lib('lang')->locale('web');
     $controller = isAke(static::$route, 'controller', false);
     $action = isAke(static::$route, 'action', false);
     $file = APPLICATION_PATH . DS . 'front' . DS . 'controllers' . DS . $controller . '.php';
     $tpl = APPLICATION_PATH . DS . 'front' . DS . 'views' . DS . $controller . DS . $action . '.phtml';
     if (!File::exists($file)) {
         static::is404();
     }
     require_once $file;
     $class = 'Thin\\' . ucfirst($controller) . 'Controller';
     $i = new $class();
     if (File::exists($tpl)) {
         $i->view = new Container();
         if (static::$pjax) {
             $i->view->partial = function ($partial) {
                 return true;
             };
         } else {
             $i->view->partial = function ($partial) use($i) {
                 $tpl = APPLICATION_PATH . DS . 'front' . DS . 'views' . DS . 'partials' . DS . $partial . '.phtml';
                 if (File::exists($tpl)) {
                     $code = View::lng(File::read($tpl));
                     $code = str_replace('$this', '$i->view', $code);
                     eval('; ?>' . $code . '<?php ;');
                 }
             };
         }
     }
     $methods = get_class_methods($i);
     $call = strtolower(static::$method) . ucfirst($action);
     if (!Arrays::in($call, $methods)) {
         static::is404();
     }
     if (Arrays::in('init', $methods)) {
         $i->init();
     }
     $i->{$call}();
     if (Arrays::in('after', $methods)) {
         $i->after();
     }
     if (File::exists($tpl)) {
         $code = View::lng(File::read($tpl));
         $code = str_replace('$this', '$i->view', $code);
         header("HTTP/1.0 200 OK");
         eval('; ?>' . $code . '<?php ;');
         exit;
     }
 }
Example #27
0
 public function select($what)
 {
     /* polymorphism */
     if (is_string($what)) {
         if (fnmatch('*,*', $what)) {
             $what = str_replace(' ', '', $what);
             $what = explode(',', $what);
         }
     }
     if (Arrays::is($what)) {
         foreach ($what as $seg) {
             if (!Arrays::in($seg, $this->selects)) {
                 $this->selects[] = $seg;
             }
         }
     } else {
         if (!Arrays::in($what, $this->selects)) {
             $this->selects[] = $what;
         }
     }
     return $this;
 }
Example #28
0
 private function _analyze()
 {
     $values = $this->values();
     foreach ($values as $k => $v) {
         if (!Arrays::in($k, $this->_fields)) {
             $this->{$k} = $v;
         }
     }
     return $this;
 }
Example #29
0
 /**
  * Receives lines from the remote host and looks for expected response codes.
  * @param array $codes   A list of one or more expected response codes
  * @param int $timeout   The timeout for this individual command, if any
  * @return string        The last text message received
  * @throws Exception
  */
 protected function expect($codes, $timeout = null)
 {
     if (!Arrays::is($codes)) {
         $codes = (array) $codes;
     }
     $code = null;
     $text = '';
     try {
         $text = $line = $this->recv($timeout);
         while (preg_match("/^[0-9]+-/", $line)) {
             $line = $this->recv($timeout);
             $text .= $line;
         }
         sscanf($line, '%d%s', $code, $text);
         if ($code === null || !Arrays::in($code, $codes)) {
             throw new Exception($line);
         }
     } catch (Exception $e) {
         // no response in expect() probably means that the
         // remote server forcibly closed the connection so
         // lets clean up on our end as well?
         $this->debug('No response in expect(): ' . $e->getMessage());
         $this->disconnect(false);
     }
     return $text;
 }
Example #30
0
 public function __call($func, $args)
 {
     if (substr($func, 0, strlen('get')) == 'get') {
         $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, strlen('get'))));
         $field = Inflector::lower($uncamelizeMethod);
         $default = count($args) == 1 ? Arrays::first($args) : null;
         $res = isAke($this->_data, $field, false);
         if (false !== $res) {
             return $res;
         } else {
             $resFk = isAke($this->_data, $field . '_id', false);
             if (false !== $resFk) {
                 $db = Db::instance($this->_db->db, $field);
                 $object = count($args) == 1 ? $args[0] : false;
                 if (!is_bool($object)) {
                     $object = false;
                 }
                 return $db->find($resFk, $object);
             } else {
                 if ($field[strlen($field) - 1] == 's' && isset($this->_data[$this->_db->pk()]) && $field[0] != '_') {
                     $db = Db::instance($this->_db->db, substr($field, 0, -1));
                     $object = count($args) == 1 ? $args[0] : false;
                     if (!is_bool($object)) {
                         $object = false;
                     }
                     $idField = $this->_db->table . '_id';
                     return $db->where([$idField, '=', $this->_data[$this->_db->pk()]])->exec($object);
                 } else {
                     return $default;
                 }
             }
         }
     } elseif (substr($func, 0, strlen('has')) == 'has') {
         $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, strlen('has'))));
         $field = Inflector::lower($uncamelizeMethod);
         $res = isAke($this->_data, $field, false);
         if (false !== $res) {
             return true;
         } else {
             $resFk = isAke($this->_data, $field . '_id', false);
             if (false !== $resFk) {
                 return true;
             } else {
                 if ($field[strlen($field) - 1] == 's' && isset($this->_data[$this->_db->pk()]) && $field[0] != '_') {
                     $db = Db::instance($this->_db->db, substr($field, 0, -1));
                     $idField = $this->_db->table . '_id';
                     $count = $db->where([$idField, '=', $this->_data[$this->_db->pk()]])->count();
                     return $count > 0 ? true : false;
                 }
             }
         }
         return false;
     } elseif (substr($func, 0, strlen('set')) == 'set') {
         $fields = $this->_db->fieldsSave();
         $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($func, strlen('set'))));
         $field = Inflector::lower($uncamelizeMethod);
         if (!in_array($field, $fields) && $field != $this->_db->pk()) {
             throw new Exception("The field {$field} does not exist in the model.");
         }
         if (!empty($args)) {
             $val = Arrays::first($args);
         } else {
             $val = null;
         }
         if (is_object($val)) {
             $val = $val->id;
         }
         if (fnmatch('*_id', $field)) {
             if (is_numeric($val)) {
                 $val = (int) $val;
             }
         }
         $this->_data[$field] = $val;
         $autosave = isAke($this->_data, 'autosave', false);
         return !$autosave ? $this : $this->save();
     } else {
         $cb = isake($this->_events, $func, false);
         if (false !== $cb) {
             if ($cb instanceof Closure) {
                 return call_user_func_array($cb, $args);
             }
         } else {
             if ($func[strlen($func) - 1] == 's' && isset($this->_data[$this->_db->pk()]) && $func[0] != '_') {
                 $db = Db::instance($this->_db->db, substr($func, 0, -1));
                 $object = count($args) == 1 ? $args[0] : false;
                 if (!is_bool($object)) {
                     $object = false;
                 }
                 $idField = $this->_db->table . '_id';
                 return $db->where([$idField, '=', $this->_data[$this->_db->pk()]])->exec($object);
             } else {
                 $auth = ['checkIndices', '_hooks'];
                 if (Arrays::in($func, $auth)) {
                     return true;
                 }
                 throw new Exception("{$func} is not a model function of {$this->_db}.");
             }
         }
     }
 }