Beispiel #1
0
 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];
 }
Beispiel #2
0
 public static function __callStatic($method, $args)
 {
     if (count($args)) {
         $type = Inflector::upper($method);
         $fnArgs = array_merge([$type], $args);
         return call_user_func_array('staticLog', $fnArgs);
     }
     throw new Exception('You must provide a message to log.');
 }
Beispiel #3
0
 /**
  * Creates a new request with values from PHP's super globals.
  *
  * @return Request A new request
  *
  * @api
  */
 public static function createFromGlobals()
 {
     $request = new static($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER);
     if ((0 === strpos($request->server->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded') || 0 === strpos($request->server->get('HTTP_CONTENT_TYPE'), 'application/x-www-form-urlencoded')) && in_array(\Thin\Inflector::upper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH'))) {
         parse_str($request->getContent(), $data);
         if (magic_quotes()) {
             $data = arrayStripslashes($data);
         }
         $request->request = new ParameterBag($data);
     }
     return $request;
 }
Beispiel #4
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.");
 }
Beispiel #5
0
 public function order($fieldOrder = 'date_create', $orderDirection = 'ASC', $results = array())
 {
     $res = count($results) ? $results : $this->results;
     $fields = $this->fields;
     $fields['id'] = array();
     $fields['date_create'] = array();
     if (!Arrays::is($fieldOrder)) {
         if (null !== $fieldOrder && !Arrays::exists($fieldOrder, $fields)) {
             $fields[$fieldOrder] = array();
         }
     } else {
         foreach ($fields as $tmpField => $info) {
             if (null !== $tmpField && !Arrays::exists($tmpField, $fields)) {
                 $fields[$tmpField] = array();
             }
         }
     }
     $sort = array();
     foreach ($res as $id) {
         $objectCreated = $this->row($id);
         foreach ($fields as $key => $infos) {
             $type = Arrays::exists('type', $fields[$key]) ? $fields[$key]['type'] : null;
             if ('data' == $type) {
                 list($dummy, $foreignTable, $foreignFieldKey) = $fields[$key]['contentList'];
                 $foreignFields = Arrays::exists($foreignTable, Data::$_fields) ? Data::$_fields[$foreignTable] : Data::noConfigFields($foreignTable);
                 $foreignStorage = new self($foreignTable);
                 $foreignRow = $foreignStorage->find($objectCreated->{$key});
                 $foreignFieldKeys = explode(',', $foreignFieldKey);
                 $value = '';
                 for ($i = 0; $i < count($foreignFieldKey); $i++) {
                     $tmpKey = $foreignFieldKey[$i];
                     $value .= $foreignRow->{$tmpKey} . ' ';
                 }
                 $value = substr($value, 0, -1);
             } else {
                 $value = isset($objectCreated->{$key}) ? $objectCreated->{$key} : null;
             }
             $sort[$key][] = $value;
         }
     }
     $asort = array();
     foreach ($sort as $key => $rows) {
         for ($i = 0; $i < count($rows); $i++) {
             if (empty(${$key}) || is_string(${$key})) {
                 ${$key} = array();
             }
             $asort[$i][$key] = $rows[$i];
             array_push(${$key}, $rows[$i]);
         }
     }
     if (Arrays::is($fieldOrder) && !Arrays::is($orderDirection)) {
         $t = array();
         foreach ($fieldOrder as $tmpField) {
             array_push($t, $orderDirection);
         }
         $orderDirection = $t;
     }
     if (Arrays::is($fieldOrder) && Arrays::is($orderDirection)) {
         if (count($orderDirection) < count($fieldOrder)) {
             throw new Exception('You must provide the same arguments number of fields sorting and directions sorting.');
         }
         if (count($fieldOrder) == 1) {
             $fieldOrder = Arrays::first($fieldOrder);
             if ('ASC' == Inflector::upper(Arrays::first($orderDirection))) {
                 array_multisort(${$fieldOrder}, SORT_ASC, $asort);
             } else {
                 array_multisort(${$fieldOrder}, SORT_DESC, $asort);
             }
         } elseif (count($fieldOrder) > 1) {
             $params = array();
             foreach ($fieldOrder as $k => $tmpField) {
                 $tmpSort = isset($orderDirection[$k]) ? $orderDirection[$k] : 'ASC';
                 $params[] = ${$tmpField};
                 $params[] = 'ASC' == $tmpSort ? SORT_ASC : SORT_DESC;
             }
             $params[] = $asort;
             call_user_func_array('array_multisort', $params);
         }
     } else {
         if ('ASC' == Inflector::upper($orderDirection)) {
             array_multisort(${$fieldOrder}, SORT_ASC, $asort);
         } else {
             array_multisort(${$fieldOrder}, SORT_DESC, $asort);
         }
     }
     $collection = array();
     foreach ($asort as $key => $row) {
         $tmpId = $row['id'];
         array_push($collection, $tmpId);
     }
     $this->results = $collection;
     return $this;
 }
Beispiel #6
0
 function ThinLog($message, $logFile = null, $type = 'info')
 {
     if (null === $logFile) {
         $logFile = LOGS_PATH . DS . date('Y-m-d') . '.log';
     } else {
         if (false === File::exists($logFile)) {
             File::create($logFile);
         }
     }
     File::append($logFile, date('Y-m-d H:i:s') . "\t" . Inflector::upper($type) . "\t{$message}\n");
 }
Beispiel #7
0
 public function order($fieldOrder, $orderDirection = 'ASC', $results = array())
 {
     $res = count($results) ? $results : $this->results;
     if (empty($res)) {
         return $this;
     }
     $fields = array_keys(Arrays::first($res));
     $sort = array();
     foreach ($res as $i => $tab) {
         foreach ($fields as $k) {
             $value = isAke($tab, $k, null);
             $sort[$k][] = $value;
         }
     }
     $asort = array();
     foreach ($sort as $key => $rows) {
         for ($i = 0; $i < count($rows); $i++) {
             if (empty(${$key}) || is_string(${$key})) {
                 ${$key} = array();
             }
             $asort[$i][$key] = $rows[$i];
             array_push(${$key}, $rows[$i]);
         }
     }
     if (Arrays::is($fieldOrder) && !Arrays::is($orderDirection)) {
         $t = array();
         foreach ($fieldOrder as $tmpField) {
             array_push($t, $orderDirection);
         }
         $orderDirection = $t;
     }
     if (Arrays::is($fieldOrder) && Arrays::is($orderDirection)) {
         if (count($orderDirection) < count($fieldOrder)) {
             throw new Exception('You must provide the same arguments number of fields sorting and directions sorting.');
         }
         if (count($fieldOrder) == 1) {
             $fieldOrder = Arrays::first($fieldOrder);
             if ('ASC' == Inflector::upper(Arrays::first($orderDirection))) {
                 array_multisort(${$fieldOrder}, SORT_ASC, $asort);
             } else {
                 array_multisort(${$fieldOrder}, SORT_DESC, $asort);
             }
         } elseif (count($fieldOrder) > 1) {
             $params = array();
             foreach ($fieldOrder as $k => $tmpField) {
                 $tmpSort = isset($orderDirection[$k]) ? $orderDirection[$k] : 'ASC';
                 $params[] = ${$tmpField};
                 $params[] = 'ASC' == $tmpSort ? SORT_ASC : SORT_DESC;
             }
             $params[] = $asort;
             call_user_func_array('array_multisort', $params);
         }
     } else {
         if ('ASC' == Inflector::upper($orderDirection)) {
             array_multisort(${$fieldOrder}, SORT_ASC, $asort);
         } else {
             array_multisort(${$fieldOrder}, SORT_DESC, $asort);
         }
     }
     $collection = array();
     foreach ($asort as $key => $row) {
         array_push($collection, $row);
     }
     $this->results = $collection;
     return $this;
 }
Beispiel #8
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 (!Arrays::in($object, $fields) && 'id' != $object) {
                 $object = Arrays::in($object . '_id', $fields) ? $object . '_id' : $object;
             }
             $direction = !empty($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, strlen('findLastBy'));
     $object = Inflector::uncamelize(lcfirst(substr($fn, strlen('findLastBy'))));
     if (strlen($fn) > strlen('findLastBy')) {
         if ('findLastBy' == $method) {
             $obj = count($args) == 2 ? $args[1] : true;
             if (!is_bool($obj)) {
                 $obj = true;
             }
             return $this->where([$object, '=', Arrays::first($args)])->last($obj);
         }
     }
     $method = substr($fn, 0, 11);
     $object = Inflector::uncamelize(lcfirst(substr($fn, 11)));
     if (strlen($fn) > 11) {
         if ('findFirstBy' == $method) {
             $obj = count($args) == 2 ? $args[1] : true;
             if (!is_bool($obj)) {
                 $obj = true;
             }
             return $this->where([$object, '=', Arrays::first($args)])->first($obj);
         }
     }
     $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)]);
             }
         }
     }
     $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([$field, '=', $idFk], $op);
         }
     }
     if (!empty($args) && Arrays::first($args) instanceof Closure) {
         $closure = Arrays::first($args);
         array_shift($args);
         return call_user_func_array($closure, $args);
     }
     throw new Exception("Method '{$fn}' is unknown.");
 }
Beispiel #9
0
 function getSetting($code, $id = true)
 {
     $setting = Model::Setting()->firstOrCreate(['code' => Inflector::upper($code)]);
     return $id ? $setting->id : $setting;
 }
Beispiel #10
0
 /**
  * Build a WHERE or HAVING clause
  * @param string $type
  * @return string
  */
 protected function _buildConditions($type)
 {
     $conditions_class_property_name = "_{$type}_conditions";
     // If there are no clauses, return empty string
     if (count($this->{$conditions_class_property_name}) === 0) {
         return '';
     }
     $conditions = [];
     foreach ($this->{$conditions_class_property_name} as $condition) {
         $conditions[] = $condition[self::CONDITION_FRAGMENT];
         $this->_values = array_merge($this->_values, $condition[self::CONDITION_VALUES]);
     }
     return Inflector::upper($type) . " " . join(" AND ", $conditions);
 }
Beispiel #11
0
 public function urlsite($echo = true)
 {
     if (null === static::$urlsite) {
         $protocol = 'http';
         if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
             $protocol = 'https';
         }
         container()->setProtocol($protocol);
         $urlSite = "{$protocol}://" . $_SERVER["SERVER_NAME"] . "/";
         if (strstr($urlSite, '//')) {
             $urlSite = repl('//', '/', $urlSite);
             $urlSite = repl($protocol . ':/', $protocol . '://', $urlSite);
         }
         if (Inflector::upper(substr(PHP_OS, 0, 3)) === 'WIN') {
             $tab = explode('\\', $urlSite);
             $r = '';
             foreach ($tab as $c => $v) {
                 $r .= $v;
             }
             $r = repl('//', '/', $r);
             $r = repl($protocol . ':/', $protocol . '://', $r);
             $urlSite = $r;
         }
         static::$urlsite = $urlSite;
     }
     if (false === $echo) {
         return static::$urlsite;
     } else {
         echo static::$urlsite;
         return;
     }
 }
Beispiel #12
0
 public function where($condition = [], $op = 'AND')
 {
     $op = Inflector::upper($op);
     $rows = [];
     $check = isAke($this->wheres, sha1(serialize(func_get_args())), false);
     if (!$check) {
         if (!empty($condition)) {
             $rows = [];
             if (!Arrays::is($condition)) {
                 $condition = str_replace([' LIKE START ', ' LIKE END ', ' NOT LIKE ', ' NOT IN '], [' LIKESTART ', ' LIKEEND ', ' NOTLIKE ', ' NOTIN '], $condition);
                 if (fnmatch('* = *', $condition)) {
                     list($field, $value) = explode(' = ', $condition, 2);
                     $operand = '=';
                 } elseif (fnmatch('* < *', $condition)) {
                     list($field, $value) = explode(' < ', $condition, 2);
                     $operand = '<';
                 } elseif (fnmatch('* > *', $condition)) {
                     list($field, $value) = explode(' > ', $condition, 2);
                     $operand = '>';
                 } elseif (fnmatch('* <= *', $condition)) {
                     list($field, $value) = explode(' <= ', $condition, 2);
                     $operand = '<=';
                 } elseif (fnmatch('* >= *', $condition)) {
                     list($field, $value) = explode(' >= ', $condition, 2);
                     $operand = '>=';
                 } elseif (fnmatch('* LIKESTART *', $condition)) {
                     list($field, $value) = explode(' LIKESTART ', $condition, 2);
                     $operand = 'LIKESTART';
                 } elseif (fnmatch('* LIKEEND *', $condition)) {
                     list($field, $value) = explode(' LIKEEND ', $condition, 2);
                     $operand = 'LIKEEND';
                 } elseif (fnmatch('* NOTLIKE *', $condition)) {
                     list($field, $value) = explode(' NOTLIKE ', $condition, 2);
                     $operand = 'NOTLIKE';
                 } elseif (fnmatch('* LIKE *', $condition)) {
                     list($field, $value) = explode(' LIKE ', $condition, 2);
                     $operand = 'LIKE';
                 } elseif (fnmatch('* IN *', $condition)) {
                     list($field, $value) = explode(' IN ', $condition, 2);
                     $operand = 'IN';
                 } elseif (fnmatch('* NOTIN *', $condition)) {
                     list($field, $value) = explode(' NOTIN ', $condition, 2);
                     $operand = 'NOTIN';
                 } elseif (fnmatch('* != *', $condition)) {
                     list($field, $value) = explode(' != ', $condition, 2);
                     $operand = '!=';
                 } elseif (fnmatch('* <> *', $condition)) {
                     list($field, $value) = explode(' <> ', $condition, 2);
                     $operand = '<>';
                 }
                 $condition = [$field, $operand, $value];
             } else {
                 list($field, $operand, $value) = $condition;
             }
             if (true === $this->useCache) {
                 $keyAge = 'fdb.where.age.' . $this->collection . '.' . sha1(serialize($condition));
                 $keyData = 'fdb.where.data.' . $this->collection . '.' . sha1(serialize($condition));
                 $ageDb = $this->getAge();
                 $ageQuery = $this->cache()->get($keyAge);
                 if (strlen($ageQuery)) {
                     if ($ageQuery > $ageDb) {
                         $rows = $this->cache()->get($keyData);
                     }
                 }
             }
             if (empty($rows)) {
                 $values = [];
                 $files = $this->getFiles('fields.' . $field);
                 if (!empty($files)) {
                     foreach ($files as $file) {
                         $id = (int) str_replace('.db', '', Arrays::last(explode('/', $file)));
                         $values[$id] = File::read($file);
                     }
                 }
                 foreach ($values as $id => $tmpValue) {
                     $row = [];
                     $val = unserialize($tmpValue);
                     $checkValue = $this->compare($val, $operand, $value);
                     if ($checkValue) {
                         $rows[$id] = $val;
                     }
                 }
                 if (true === $this->useCache) {
                     $this->cache()->set($keyData, $rows);
                     $this->cache()->set($keyAge, time());
                 }
             }
             if (empty($this->wheres)) {
                 $this->results = $rows;
             } else {
                 $made = false;
                 if (true === $this->useCache) {
                     $keyAge = 'fdb.where.make.age.' . $this->collection . '.' . sha1(serialize(array_keys($this->wheres)) . serialize($condition));
                     $keyData = 'fdb.where.make.data.' . $this->collection . '.' . sha1(serialize(array_keys($this->wheres)) . serialize($condition));
                     $ageDb = $this->getAge();
                     $ageQuery = $this->cache()->get($keyAge);
                     if (strlen($ageQuery)) {
                         if ($ageQuery > $ageDb) {
                             $this->results = $this->cache()->get($keyData);
                             $made = true;
                         }
                     }
                 }
                 if (!$made) {
                     if (strtoupper($op) == 'AND') {
                         $this->results = $this->intersect($rows, $this->results);
                     } elseif (strtoupper($op) == 'OR') {
                         $this->results = $this->merge($this->results, $rows);
                     }
                     $this->cache()->set($keyData, $this->results);
                     $this->cache()->set($keyAge, time());
                 }
             }
             $this->wheres[sha1(serialize(func_get_args()))] = true;
         }
     }
     return $this;
 }
Beispiel #13
0
 public function resolveType($type)
 {
     if (is_numeric($type)) {
         return (int) $type;
     }
     $type = Inflector::upper($type);
     static $types = array('DOUBLE' => 1, 'STRING' => 2, 'OBJECT' => 3, 'ARRAY' => 4, 'BINARY' => 5, 'ID' => 8, 'BOOL' => 8, 'BOOLEAN' => 8, 'DATE' => 9, 'NULL' => 10, 'REGEX' => 11, 'JAVASCRIPT' => 13, 'CODE' => 13, 'SYMBOL' => 14, 'JAVASCRIPT_SCOPE' => 15, 'CODE_SCOPE' => 15, 'INT32' => 16, 'TS' => 17, 'TIMESTAMP' => 17, 'INT64' => 18, 'MIN' => -1, 'MAX' => 127);
     if (!isset($types[$type])) {
         throw new \InvalidArgumentException('Type "' . $type . '" could not be resolved');
     }
     return $types[$type];
 }
Beispiel #14
0
 public static function order($type, $results, $field = 'date_create', $orderDirection = 'ASC')
 {
     $settings = Arrays::exists($type, static::$_settings) ? static::$_settings[$type] : static::defaultConfig($type);
     $hook = Arrays::exists('order', $settings) ? $settings['order'] : null;
     static::_hook($hook, func_get_args(), 'before');
     $queryKey = sha1(serialize(func_get_args()));
     $cache = static::cache($type, $queryKey);
     if (null !== $cache) {
         return $cache;
     }
     $fields = static::getModel($type);
     $fields['id'] = array();
     $fields['date_create'] = array();
     if (!Arrays::is($field)) {
         if (null !== $field && !Arrays::exists($field, $fields)) {
             $fields[$field] = array();
         }
     } else {
         foreach ($field as $tmpField) {
             if (null !== $tmpField && !Arrays::exists($tmpField, $fields)) {
                 $fields[$tmpField] = array();
             }
         }
     }
     $sort = array();
     foreach ($results as $object) {
         $path = static::makePath($type, $object);
         $objectCreated = static::getObject($path, $type);
         foreach ($fields as $key => $infos) {
             $value = isset($objectCreated->{$key}) ? $objectCreated->{$key} : null;
             $sort[$key][] = $value;
         }
     }
     $asort = array();
     foreach ($sort as $key => $rows) {
         for ($i = 0; $i < count($rows); $i++) {
             if (empty(${$key}) || is_string(${$key})) {
                 ${$key} = array();
             }
             $asort[$i][$key] = $rows[$i];
             array_push(${$key}, $rows[$i]);
         }
     }
     if (Arrays::is($field) && Arrays::is($orderDirection)) {
         if (count($field) == 2) {
             $first = Arrays::first($field);
             $second = Arrays::last($field);
             if ('ASC' == Inflector::upper(Arrays::first($orderDirection)) && 'ASC' == Inflector::upper(end($orderDirection))) {
                 array_multisort(${$first}, SORT_ASC, ${$second}, SORT_ASC, $asort);
             } elseif ('DESC' == Inflector::upper(Arrays::first($orderDirection)) && 'ASC' == Inflector::upper(end($orderDirection))) {
                 array_multisort(${$first}, SORT_DESC, ${$second}, SORT_ASC, $asort);
             } elseif ('DESC' == Inflector::upper(Arrays::first($orderDirection)) && 'DESC' == Inflector::upper(end($orderDirection))) {
                 array_multisort(${$first}, SORT_DESC, ${$second}, SORT_DESC, $asort);
             } elseif ('ASC' == Inflector::upper(Arrays::first($orderDirection)) && 'DESC' == Inflector::upper(end($orderDirection))) {
                 array_multisort(${$first}, SORT_ASC, ${$second}, SORT_DESC, $asort);
             }
         }
     } else {
         if ('ASC' == Inflector::upper($orderDirection)) {
             array_multisort(${$field}, SORT_ASC, $asort);
         } else {
             array_multisort(${$field}, SORT_DESC, $asort);
         }
     }
     $collection = array();
     foreach ($asort as $key => $row) {
         $tmpId = $row['id'];
         $tmpObject = static::getById($type, $tmpId);
         array_push($collection, $tmpObject);
     }
     $cache = static::cache($type, $queryKey, $collection);
     static::_hook($hook, func_get_args(), 'after');
     return $collection;
 }
Beispiel #15
0
 /**
  * Perform a http call against an url with an optional payload
  *
  * @return array
  * @param string $url
  * @param string $method (GET/POST/PUT/DELETE)
  * @param array|bool $payload The document/instructions to pass along
  * @throws HTTPException
  */
 protected function call($url, $method = "GET", $payload = null)
 {
     $conn = $this->ch;
     $protocol = "http";
     $requestURL = $protocol . "://" . $this->host . $url;
     curl_setopt($conn, CURLOPT_URL, $requestURL);
     curl_setopt($conn, CURLOPT_TIMEOUT, $this->timeout);
     curl_setopt($conn, CURLOPT_PORT, $this->port);
     curl_setopt($conn, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($conn, CURLOPT_CUSTOMREQUEST, Inflector::upper($method));
     curl_setopt($conn, CURLOPT_FORBID_REUSE, 0);
     if (Arrays::is($payload) && count($payload) > 0) {
         curl_setopt($conn, CURLOPT_POSTFIELDS, json_encode($payload));
     } else {
         curl_setopt($conn, CURLOPT_POSTFIELDS, $payload);
     }
     $response = curl_exec($conn);
     if ($response !== false) {
         $data = json_decode($response, true);
         if (!$data) {
             $data = array('error' => $response, "code" => curl_getinfo($conn, CURLINFO_HTTP_CODE));
         }
     } else {
         /**
          * cUrl error code reference can be found here:
          * http://curl.haxx.se/libcurl/c/libcurl-errors.html
          */
         $errno = curl_errno($conn);
         switch ($errno) {
             case CURLE_UNSUPPORTED_PROTOCOL:
                 $error = "Unsupported protocol [{$protocol}]";
                 break;
             case CURLE_FAILED_INIT:
                 $error = "Internal cUrl error?";
                 break;
             case CURLE_URL_MALFORMAT:
                 $error = "Malformed URL [{$requestURL}] -d " . json_encode($payload);
                 break;
             case CURLE_COULDNT_RESOLVE_PROXY:
                 $error = "Couldn t resolve proxy";
                 break;
             case CURLE_COULDNT_RESOLVE_HOST:
                 $error = "Couldn t resolve host";
                 break;
             case CURLE_COULDNT_CONNECT:
                 $error = "Couldn t connect to host [{$this->host}], ElasticSearch down?";
                 break;
             case CURLE_OPERATION_TIMEDOUT:
                 $error = "Operation timed out on [{$requestURL}]";
                 break;
             default:
                 $error = "Unknown error";
                 if ($errno == 0) {
                     $error .= ". Non-cUrl error";
                 }
                 break;
         }
         $exception = new HTTPException($error);
         $exception->payload = $payload;
         $exception->port = $this->port;
         $exception->protocol = $protocol;
         $exception->host = $this->host;
         $exception->method = $method;
         throw $exception;
     }
     return $data;
 }
Beispiel #16
0
 public function order($field, $direction = 'ASC')
 {
     $direction = Inflector::upper($direction);
     $this->orders[] = array($field, $direction);
     return $this;
 }
Beispiel #17
0
 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);
 }
Beispiel #18
0
 public function describe()
 {
     $desc = array();
     $q = 'DESCRIBE ' . $this->_entity . '.' . $this->_table;
     $res = $this->query($q, false);
     $count = count($res);
     if (0 < $count) {
         $field = 0;
         $type = 1;
         $null = 2;
         $key = 3;
         $default = 4;
         $extra = 5;
         $i = 1;
         $p = 1;
         foreach ($res as $row) {
             list($length, $scale, $precision, $unsigned, $primary, $index, $primaryPosition, $identity) = array(null, null, null, null, false, false, null, false);
             if (preg_match('/unsigned/', $row[$type])) {
                 $unsigned = true;
             }
             if (preg_match('/^((?:var)?char)\\((\\d+)\\)/', $row[$type], $matches)) {
                 $row[$type] = $matches[1];
                 $length = $matches[2];
             } else {
                 if (preg_match('/^decimal\\((\\d+),(\\d+)\\)/', $row[$type], $matches)) {
                     $row[$type] = 'decimal';
                     $precision = $matches[1];
                     $scale = $matches[2];
                 } else {
                     if (preg_match('/^float\\((\\d+),(\\d+)\\)/', $row[$type], $matches)) {
                         $row[$type] = 'float';
                         $precision = $matches[1];
                         $scale = $matches[2];
                     } else {
                         if (preg_match('/^((?:big|medium|small|tiny)?int)\\((\\d+)\\)/', $row[$type], $matches)) {
                             $row[$type] = $matches[1];
                             // The optional argument of a MySQL int type is not precision
                             // or length; it is only a hint for display width.
                         }
                     }
                 }
             }
             if (strlen($row[$key])) {
                 if (Inflector::upper($row[$key]) == 'PRI') {
                     $primary = true;
                     $primaryPosition = $p;
                     if ($row[$extra] == 'auto_increment') {
                         $identity = true;
                         $index = true;
                     } else {
                         $identity = false;
                     }
                     ++$p;
                 } else {
                     $index = true;
                 }
             }
             $desc[$this->foldCase($row[$field])] = array('ENTITY_NAME' => $this->foldCase($this->_entity), 'TABLE_NAME' => $this->foldCase($this->_table), 'COLUMN_NAME' => $this->foldCase($row[$field]), 'COLUMN_POSITION' => $i, 'DATA_TYPE' => $row[$type], 'DEFAULT' => $row[$default], 'NULLABLE' => (bool) ($row[$null] == 'YES'), 'LENGTH' => $length, 'SCALE' => $scale, 'PRECISION' => $precision, 'UNSIGNED' => $unsigned, 'PRIMARY' => $primary, 'PRIMARY_POSITION' => $primaryPosition, 'INDEX' => $index, 'IDENTITY' => $identity);
             ++$i;
         }
     }
     return $desc;
 }