public function __construct($table, $fields) { /* polymorphism */ $fields = !Arrays::is($fields) ? strstr($fields, ',') ? explode(',', repl(' ', '', $fields)) : [$fields] : $fields; $this->table = $table; $this->fields = $fields; }
/** * Creates a new navigation container * * @param array $pages [optional] pages to add * @throws Exception if $pages is invalid */ public function __construct($pages = null) { if (Arrays::is($pages)) { $this->addPages($pages); } elseif (null !== $pages) { throw new Exception('Invalid argument: $pages must be an array or null'); } }
/** * where() * Sets where object * @access public * @param string $where * @param string $value * @return \Thin\Webquery */ public function where($where = null, $value = null) { if (Arrays::is($this->where)) { $this->whereKey = count($this->where) + 1; } $this->where[$this->whereKey]['attr'] = $where; $this->where[$this->whereKey]['value'] = $value; return $this; }
/** * Construct new RangeQuery component * * @return \ElasticSearch\DSL\RangeQuery * @param array $options */ public function __construct(array $options = []) { $this->fieldname = key($options); $values = Arrays::first($options); if (Arrays::is($values)) { foreach ($values as $key => $val) { $this->{$key} = $val; } } }
public function __construct($db, $table, $fields) { /* CLI case */ if (!defined('APPLICATION_ENV')) { define('APPLICATION_ENV', 'production'); } /* polymorphism */ $fields = !Arrays::is($fields) ? strstr($fields, ',') ? explode(',', repl(' ', '', $fields)) : [$fields] : $fields; $this->table = $table; $this->fields = $fields; $this->model = jdb($db, $this->table); }
/** * Get or set a config * * @param string $key * @param mixed $value * @throws \Exception * @return array|void */ public function config($key, $value = null) { if (Arrays::is($key)) { $this->config = $key + $this->config; } else { if ($value !== null) { $this->config[$key] = $value; } if (!isset($this->config[$key])) { throw new Exception("Configuration key `type` is not set"); } return $this->config[$key]; } }
/** * Custom arrayReplaceRecursive to be used if PHP < 5.3 * Replaces elements from passed arrays into the first array recursively * * @param array $array1 The array in which elements are replaced * @param array $array2 The array from which elements will be extracted * * @return array Returns an array, or NULL if an error occurs. */ public static function arrayReplaceRecursive($array1, $array2) { if (function_exists('arrayReplaceRecursive')) { return arrayReplaceRecursive($array1, $array2); } foreach ($array2 as $key => $value) { if (Arrays::is($value)) { $array1[$key] = self::arrayReplaceRecursive($array1[$key], $value); } else { $array1[$key] = $value; } } return $array1; }
/** * Add a model item or model array or ModelSet to this set * * @param mixed $items model item or arry or ModelSet to add * * @return $this */ public function add($items) { if ($items && $items instanceof Container) { $id = (int) $items->id(); $this->_items[$id] = $items; } elseif (Arrays::is($items)) { foreach ($items as $obj) { if ($obj instanceof Container) { $this->add($obj); } } } elseif ($items instanceof self) { $this->add($items->toArray()); } return $this; }
public function query($query, $meta = []) { $q = json_encode($query); $q = urlencode($q); $url = $this->uri . '/db/' . $this->db . '/collection/' . $this->col . '/apiKey/' . $this->apiKey . '/query/' . $q; if (!empty($meta)) { $mv = []; foreach ($meta as $k => $v) { if (Arrays::is($v)) { $v = json_encode($v); } $mv[] = $k . '=' . $v; } $mv = implode('&', $mv); $url .= '&' . $mv; } $ret = $this->request->get($url); return json_decode($ret, true); }
/** * Build the DSL as array * * @throws \ElasticSearch\Exception * @return array */ public function build() { $built = []; if ($this->from != null) { $built['from'] = $this->from; } if ($this->size != null) { $built['size'] = $this->size; } if ($this->sort && Arrays::is($this->sort)) { $built['sort'] = $this->sort; } if (!$this->query) { throw new \ElasticSearch\Exception("Query must be specified"); } else { $built['query'] = $this->query->build(); } return $built; }
/** * Search * * @return array * @param array|string $query * @throws \ElasticSearch\Exception */ public function search($query) { if (Arrays::is($query)) { if (Arrays::exists("query", $query)) { $dsl = new Stringify($query); $q = (string) $dsl; $url = $this->buildUrl(array($this->type, "_search?q=" . $q)); $result = json_decode(redis()->get($url), true); return $result; } throw new \ElasticSearch\Exception("Redis protocol doesn t support the full DSL, only query"); } elseif (is_string($query)) { /** * String based search means http query string search */ $url = $this->buildUrl(array($this->type, '_search?q=' . $query)); $result = json_decode(redis()->get($url), true); return $result; } }
public static function make($db, $what) { if (is_string($what)) { $file = APPLICATION_PATH . DS . 'models' . DS . 'Bigdata' . DS . 'views' . DS . $db->db . DS . ucfirst(I::lower($db->table)) . DS . I::camelize($what) . '.php'; if (files()->exists($file)) { require_once $file; $class = '\\Thin\\' . ucfirst(I::lower($db->db)) . ucfirst(I::lower($db->table)) . 'View'; return $class::make($db); } else { return $db; } } elseif (A::is($what)) { $nameview = 'view_' . $db->db . '_' . $db->table . '_' . sha1(serialize($what)); $ageDb = $db->getage(); $viewDb = Db::instance($db->db, $nameview); $ageView = $db->getage(); $exists = strlen($db->cache()->get('dbRedis.views.' . $nameview)) ? true : false; if ($ageView < $ageDb || !$exists) { $viewDb->getCollection()->remove(); foreach ($what as $wh) { $op = 'AND'; if (count($wh) == 4) { $op = $wh[3]; unset($wh[3]); } $db = $db->where($wh); } $res = $db->exec(); foreach ($res as $row) { $viewDb->saveView($row); } $db->cache()->set('dbRedis.views.' . $nameview, 1); } return $viewDb; } }
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; }
public function keep($keys, $returnCollection = true) { /* polymorphism */ $keys = !Arrays::is($keys) ? strstr($keys, ',') ? explode(',', repl(' ', '', $keys)) : [$keys] : $keys; $results = []; if (count($this->_items)) { foreach ($this->_items as $item) { $value = []; foreach ($keys as $key) { array_push($value, isAke($item, $key, null)); } array_push($results, implode(' ', $value)); } } return true === $returnCollection ? new self($results) : $results; }
/** * Export datas to array * * @param array $ignore ignore * @param bool $recursive * @param int $deep * * @return array */ public function toArray($ignore = array('_type'), $recursive = false, $deep = 3) { if (!empty($ignore)) { $ignores = array(); foreach ($ignore as $val) { $ignores[$val] = 1; } $ignore = $ignores; } if ($recursive == true && $deep > 0) { $attrs = $this->getAttrs(); foreach ($this->cleanData as $key => $value) { if (isset($attrs[$key]) && isset($attrs[$key]['type']) && ($attrs[$key]['type'] == self::DATA_TYPE_REFERENCE || $attrs[$key]['type'] == self::DATA_TYPE_REFERENCES)) { if ($attrs[$key]['type'] == self::DATA_TYPE_REFERENCE && isset($attrs[$key]['model']) && !empty($attrs[$key]['model'])) { $model = $attrs[$key]['model']; if (!is_array($value)) { $value = (array) $value; } $obj = $model::id($value['$id']); if ($obj) { $this->cleanData[$key] = $obj->toArray($ignore, $recursive, --$deep); } } else { if ($attrs[$key]['type'] == self::DATA_TYPE_REFERENCES && isset($attrs[$key]['model']) && !empty($attrs[$key]['model'])) { $model = $attrs[$key]['model']; $data = array(); foreach ($value as $item) { if (!\Thin\Arrays::is($item)) { $item = (array) $item; } $obj = $model::id($item['$id']); if ($obj) { $data[] = $obj->toArray($ignore, $recursive, --$deep); } } if (!empty($data)) { $this->cleanData[$key] = $data; } } } } } } return array_diff_key($this->cleanData, $ignore); }
public function populate(array $datas, $namespace = null) { if (null !== $namespace) { if (!isset($this->{$namespace})) { $this->{$namespace} = []; } foreach ($datas as $k => $v) { if (Arrays::is($k)) { $this->populate($k, $namespace); } else { $this->{$namespace} = array_merge($this->{$namespace}, [$k => $v]); } } } else { foreach ($datas as $k => $v) { $id = isAke($datas, 'id', false); if (Arrays::is($v) && false === $id) { if (Arrays::isAssoc($v)) { $o = new self(); $o->populate($v); $this->{$k} = $o; } else { $this->{$k} = $v; } } else { $this->{$k} = $v; } if (!Arrays::in($k, $this->_fields)) { $this->_fields[] = $k; } } } return $this; }
/** * Provides a windows replacement for the getmxrr function. * Params and behaviour is that of the regular getmxrr function. * @see http://www.php.net/getmxrr */ protected function getmxrr($hostname, &$mxhosts, &$mxweights) { if (!Arrays::is($mxhosts)) { $mxhosts = array(); } if (!Arrays::is($mxweights)) { $mxweights = array(); } if (empty($hostname)) { return; } $cmd = 'nslookup -type=MX ' . escapeshellarg($hostname); if (!empty($this->mx_query_ns)) { $cmd .= ' ' . escapeshellarg($this->mx_query_ns); } exec($cmd, $output); if (empty($output)) { return; } $i = -1; foreach ($output as $line) { $i++; if (preg_match("/^{$hostname}\tMX preference = ([0-9]+), mail exchanger = (.+)\$/i", $line, $parts)) { $mxweights[$i] = trim($parts[1]); $mxhosts[$i] = trim($parts[2]); } if (preg_match('/responsible mail addr = (.+)$/i', $line, $parts)) { $mxweights[$i] = $i; $mxhosts[$i] = trim($parts[1]); } } return $i != -1; }
public function destroy($ids) { /* polymorphism */ $ids = Arrays::is($ids) ? $ids : func_get_args(); // We will actually pull the models from the database table and call delete on // each of them individually so that their events get fired properly with a // correct set of attributes in case the developers wants to check these. $key = $this->pk(); $rows = $this->in($key, $ids)->execute(true); $count = $rows->count(); if (0 < $count) { $rows->delete(); } // We return the total number of deletes // for the operation. The developers can then check this number as a boolean // type value or get this total count of records deleted for logging, etc. return $count; }
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; }
/** * Register an existing instance as shared in the Eventable. * * @param string $abstract * @param mixed $instance * @return void */ public function instance($abstract, $instance) { // First, we will extract the alias from the abstract if it is an array so we // are using the correct name when binding the type. If we get an alias it // will be registered with the Eventable so we can resolve it out later. if (Arrays::is($abstract)) { list($abstract, $alias) = $this->extractAlias($abstract); $this->alias($abstract, $alias); } unset($this->aliases[$abstract]); // We'll check to determine if this type has been bound before, and if it has // we will fire the rebound callbacks registered with the Eventable and it // can be updated with consuming classes that have gotten resolved here. $bound = $this->bound($abstract); $this->instances[$abstract] = $instance; if ($bound) { $this->rebound($abstract); } }
public function login($username, $password, $isSha1 = false) { $session = session(Config::get('bundle.auth.session', 'auth')); $user = $session->getUser(); if (Arrays::is($user)) { $id = isAke($user, 'id', null); if (!is_null($id)) { $user = $this->userDb->find($id); } } if (is_null($user) || !$user instanceof Container) { if (false === $isSha1) { $user = $this->userDb->username($username)->password(sha1($password))->first(true); } else { $user = $this->userDb->username($username)->password($password)->first(true); } if (!is_null($user)) { $this->user = $user; $session->setUser($user->assoc()); return true; } } else { $this->user = $user; return true; } return false; }
public function take($fields) { /* polymorphism */ $fields = !Arrays::is($fields) ? fnmatch('*,*', $fields) ? explode(',', str_replace(' ', '', $fields)) : [$fields] : $fields; $this->take = $fields; return $this; }
/** * Execute a request (with curl) * * @param string $url URL * @param mixed $parameters Array of parameters * @param string $http_method HTTP Method * @param array $http_headers HTTP Headers * @param int $form_content_type HTTP form content type to use * @return array */ private function executeRequest($url, $parameters = array(), $http_method = self::HTTP_METHOD_GET, array $http_headers = null, $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART) { $curl_options = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_CUSTOMREQUEST => $http_method); switch ($http_method) { case self::HTTP_METHOD_POST: $curl_options[CURLOPT_POST] = true; /* No break */ /* No break */ case self::HTTP_METHOD_PUT: /** * Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, * while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded. * http://php.net/manual/en/function.curl-setopt.php */ if (Arrays::is($parameters) && self::HTTP_FORM_CONTENT_TYPE_APPLICATION === $form_content_type) { $parameters = http_build_query($parameters); } $curl_options[CURLOPT_POSTFIELDS] = $parameters; break; case self::HTTP_METHOD_HEAD: $curl_options[CURLOPT_NOBODY] = true; /* No break */ /* No break */ case self::HTTP_METHOD_DELETE: case self::HTTP_METHOD_GET: if (is_array($parameters)) { $url .= '?' . http_build_query($parameters, null, '&'); } elseif ($parameters) { $url .= '?' . $parameters; } break; default: break; } $curl_options[CURLOPT_URL] = $url; $http_headers = array_merge($this->http_headers, (array) $http_headers); if (count($http_headers)) { $header = array(); foreach ($http_headers as $key => $parsed_urlvalue) { $header[] = "{$key}: {$parsed_urlvalue}"; } $curl_options[CURLOPT_HTTPHEADER] = $header; } $ch = curl_init(); curl_setopt_array($ch, $curl_options); // https handling if (!empty($this->certificate_file)) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_CAINFO, $this->certificate_file); } else { // bypass ssl verification curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); } if (!empty($this->curl_options)) { curl_setopt_array($this->curl_options); } $result = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); if ($curl_error = curl_error($ch)) { throw new Exception($curl_error, Exception::CURL_ERROR); } else { $json_decode = json_decode($result, $this->json_conversion_type); } curl_close($ch); return array('result' => null === $json_decode ? $result : $json_decode, 'code' => $http_code, 'content_type' => $content_type); }
private function checkTable($table) { $res = $this->db->prepare("SHOW TABLES"); $res->execute(); if (Arrays::is($res)) { $count = count($res); } else { $count = $res->rowCount(); } if ($count < 1) { return false; } foreach ($res as $row) { $tabletmp = Arrays::first($row); if ($table == $tabletmp) { return true; } } return false; }
private function stripslashes($val) { return Arrays::is($val) ? array_map(array(__NAMESPACE__ . '\\Tools', 'stripslashes'), $val) : stripslashes($val); }
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; }
public static function vocabulariesForm($idField, $data, $valueField = null, $required = true) { /* polymorphism */ $data = !Arrays::is($data) ? strstr($data, ',') ? explode(',', str_replace(' ', '', $data)) : [$data] : $data; $require = $required ? 'required ' : ''; $html = '<select ' . $require . 'class="form-control" name="' . $idField . '" id="' . $idField . '">' . NL; $html .= '<option value="">Choisir</option>' . NL; /* start to index 1 */ $vocables = []; $i = 1; foreach ($data as $vocable) { $vocables[$i] = $vocable; $i++; } if (count($vocables)) { foreach ($vocables as $id => $vocable) { if (1 > $id) { continue; } $selected = $valueField == $id ? 'selected ' : ''; $value = isAke($vocables, $id, ' '); $html .= '<option ' . $selected . 'value="' . $id . '">' . \Thin\Html\Helper::display($value) . '</option>' . NL; } } $html .= '</select>'; return $html; }
/** * Connect to MongoDB, select database * * @throws \Exception * @return bool */ public function connect() { if ($this->_connection) { return true; } /** * Add required variables * Clear the connection parameters for security */ $config = array('hostnames' => 'localhost:27017', 'database' => SITE_NAME); /* Add Username & Password to server string */ if (isset($config['username']) && isset($config['password'])) { $config['hostnames'] = $config['username'] . ':' . $config['password'] . '@' . $config['hostnames'] . '/' . $config['database']; } /* Add required 'mongodb://' prefix */ if (strpos($config['hostnames'], 'mongodb://') !== 0) { $config['hostnames'] = 'mongodb://' . $config['hostnames']; } if (!isset($config['options']) || !Arrays::is($config['options'])) { $config['options'] = []; } /* Create connection object, attempt to connect */ $config['options']['connect'] = false; $this->_connection = new \MongoClient($config['hostnames'], $config['options']); /* Try connect */ try { $this->_connection->connect(); } catch (\MongoConnectionException $e) { throw new \Exception('Unable to connect to MongoDB server at ' . $config['hostnames']); } if (!isset($config['database'])) { throw new \Exception('No database specified in MangoDB Config'); } $this->_db = $this->_connection->selectDB($config['database']); if (!$this->_db instanceof \MongoDB) { throw new \Exception('Unable to connect to database :: $_db is ' . gettype($this->_db)); } $this->_isConnect = true; return true; }
public function notIn($ids, $field = null) { /* polymorphism */ $ids = !Arrays::is($ids) ? strstr($ids, ',') ? explode(',', repl(' ', '', $ids)) : array($ids) : $ids; $field = is_null($field) ? $this->pk() : $field; return $this->where($field . ' NOT IN (' . implode(',', $ids) . ')'); }
function debug($var, $html = true) { if (is_null($var)) { return '<span class="null-value">[NULL]</span>'; } $out = ''; switch ($var) { case empty($var): $out = '[empty value]'; break; case Arrays::is($var): $out = var_export($var, true); break; case is_object($var): $out = var_export($var, true); break; case is_string($var): $out = $var; break; default: $out = var_export($var, true); break; } if (true === $html) { $out = "<pre>\n" . $out . "</pre>"; } return $out; }