Example #1
1
 /**
  * Converts an array, object, or string to an array.
  * 
  * @param mixed $thing Array, object, or string (JSON, serialized, or XML).
  * @return array
  */
 function to_array($thing)
 {
     if (is_array($thing)) {
         return array_build($thing);
     }
     if (is_object($thing)) {
         return array_build(object_to_array($thing));
     }
     if (is_string($thing)) {
         if (is_json($thing)) {
             return json_decode($thing, true);
         }
         if (is_serialized($thing)) {
             return to_array(unserialize($thing));
         }
         if (is_xml($thing)) {
             return xml_decode($thing, true);
         }
     }
     return (array) $thing;
 }
Example #2
0
 /**
  * Sets mail blocking preferences for a user. Eg:
  *
  * MailBlocker::setPreferences($user, [acme.blog::post.new_reply => 0])
  *
  * MailBlocker::setPreferences($user, [acme.blog::post.new_reply => 0], [fillable => [acme.blog::post.new_reply]])
  *
  * MailBlocker::setPreferences($user, [template_alias => 0], [aliases => [template_alias => acme.blog::post.new_reply]])
  *
  * Supported options:
  * - aliases: Alias definitions, with alias as key and template as value.
  * - fillable: An array of expected templates, undefined templates are ignored.
  * - verify: Only allow mail templates that are registered in the system.
  *
  * @param  array $templates Template name as key and boolean as value. If false, template is blocked. 
  * @param  RainLab\User\Models\User $user
  * @param  array $options
  * @return void
  */
 public static function setPreferences($user, $templates, $options = [])
 {
     $templates = (array) $templates;
     if (!$user) {
         throw new Exception('A user must be provided for MailBlocker::setPreferences');
     }
     extract(array_merge(['aliases' => [], 'fillable' => [], 'verify' => false], $options));
     if ($aliases) {
         $fillable = array_merge($fillable, array_values($aliases));
         $templates = array_build($templates, function ($key, $value) use($aliases) {
             return [array_get($aliases, $key, $key), $value];
         });
     }
     if ($fillable) {
         $templates = array_intersect_key($templates, array_flip($fillable));
     }
     if ($verify) {
         $existing = MailTemplate::listAllTemplates();
         $templates = array_intersect_key($templates, $existing);
     }
     $currentBlocks = array_flip(static::checkAllForUser($user));
     foreach ($templates as $template => $value) {
         // User wants to receive mail and is blocking
         if ($value && isset($currentBlocks[$template])) {
             static::removeBlock($template, $user);
         } elseif (!$value && !isset($currentBlocks[$template])) {
             static::addBlock($template, $user);
         }
     }
 }
Example #3
0
 /**
  * @inheritdoc
  */
 public function __construct($items = null, $class_slug = null, $key_by = null)
 {
     $items = is_null($items) ? [] : $items;
     if ($items instanceof \Illuminate\Support\Collection) {
         return parent::__construct($items);
     }
     if ($class_slug) {
         $items = array_map(function ($item) use($class_slug) {
             if (is_null($item)) {
                 return $item;
             }
             if (!is_array($item)) {
                 throw new \Exception("Failed to cast a model");
             }
             $class = Model::getModelClass($class_slug);
             return new $class($item);
         }, $items);
     }
     if ($key_by) {
         $items = array_build($items, function ($key, $value) use($key_by) {
             /** @var Model $value */
             $key = $value instanceof Model ? $value->get($key_by) : data_get($value, $key_by);
             return [$key, $value];
         });
     }
     return parent::__construct($items);
 }
Example #4
0
 /**
  * Same as getConfigured but uses special style structure.
  * @return mixed
  */
 public static function getConfiguredStyles($key, $default = null)
 {
     $instance = static::instance();
     $value = $instance->get($key);
     $defaultValue = $instance->getDefaultValue($key);
     if (is_array($value)) {
         $value = array_build($value, function ($key, $value) {
             return [array_get($value, 'class_name'), array_get($value, 'class_label')];
         });
     }
     return $value != $defaultValue ? $value : $default;
 }
Example #5
0
 public function getImagesAttribute()
 {
     if (!$this->image->originalFilename()) {
         return [];
     }
     return array_build($this->image->getConfig()->styles, function ($index, $style) {
         if (!($size = $style->dimensions)) {
             list($w, $h) = getimagesize($this->image->path());
             $size = "{$w}x{$h}";
         }
         return [$style->name, ['url' => $this->image->url($style->name), 'name' => $this->attributes['image_file_name'], 'dimensions' => $size, 'type' => $this->attributes['image_content_type']]];
     });
 }
 /**
  * @return \Bolt\Core\Storage\ContentCollection
  */
 public function get($wheres = array(), $loadRelated = true, $sort = null, $order = 'asc', $offset = null, $limit = null, $search = null)
 {
     $selects = $this->getSelects();
     $recordsQuery = $this->model;
     if ($loadRelated) {
         $recordsQuery = $recordsQuery->with(array('incoming', 'outgoing'));
     }
     foreach ($this->getRelationTableJoin($wheres) as $join) {
         $recordsQuery = $recordsQuery->join($join['table'], $join['left'], '=', $join['right']);
     }
     $recordsQuery = $recordsQuery->select($selects);
     foreach ($wheres as $key => $value) {
         if (is_array($value) && count($value) > 0) {
             $recordsQuery = $recordsQuery->whereIn($key, $value);
         } else {
             $recordsQuery = $recordsQuery->where($key, '=', $value);
         }
     }
     if (!is_null($search)) {
         $searchFields = $this->contentType->getSearchFields()->getDatabaseFields();
         $recordsQuery->where(function ($query) use($searchFields, $search) {
             foreach ($searchFields as $searchField) {
                 $query->orWhere(new Expression('LOWER(' . $searchField->getKey() . ')'), 'LIKE', '%' . strtolower($search) . '%');
             }
         });
     }
     $total = $recordsQuery->count();
     if (!is_null($offset)) {
         $recordsQuery = $recordsQuery->skip($offset);
     }
     if (!is_null($limit)) {
         $recordsQuery = $recordsQuery->take($limit);
     }
     if (!is_null($sort)) {
         $recordsQuery = $recordsQuery->orderBy($sort, $order);
     }
     $records = $recordsQuery->get()->toArray();
     $me = $this;
     $records = array_build($records, function ($key, $record) use($me) {
         $record = $me->callGetters($record);
         return array($record['id'], $record);
     });
     if ($loadRelated) {
         $records = $this->loadRelatedFor($records);
     }
     return $this->app['contents.factory']->create($records, $this->contentType, $total);
 }
 /**
  * @param string $result
  * @return array
  */
 protected function parseResult($result)
 {
     $rows = json_decode($result, true);
     $all = [];
     foreach ($rows as $row) {
         // Flatten the array to dot notation keys then replace dots with underscores
         $row = array_build(array_dot($row), function ($key, $value) {
             return [str_replace('.', '_', $key), $value];
         });
         if (!empty($row['month'])) {
             $row['month'] = Carbon::createFromFormat('Y-m', $row['month'])->startOfMonth()->toIso8601String();
         }
         if (!empty($row['outcome_status_date'])) {
             $row['outcome_status_date'] = Carbon::createFromFormat('Y-m', $row['outcome_status_date'])->startOfMonth()->toIso8601String();
         }
         if (!empty($row['location_latitude']) && !empty($row['location_longitude'])) {
             $row['location'] = sprintf('(%s, %s)', $row['location_latitude'], $row['location_longitude']);
         }
         $all[$row['id']] = $row;
     }
     return $all;
 }
Example #8
0
 /**
  * Parse the given filter string.
  *
  * @param  string  $filters
  * @return array
  */
 public static function parseFilters($filters)
 {
     return array_build(static::explodeFilters($filters), function ($key, $value) {
         return Route::parseFilter($value);
     });
 }
Example #9
0
 /**
  * Get the values of all registered preferences for this user, by
  * transforming their stored preferences and merging them with the defaults.
  *
  * @param string $value
  * @return array
  */
 public function getPreferencesAttribute($value)
 {
     $defaults = array_build(static::$preferences, function ($key, $value) {
         return [$key, $value['default']];
     });
     $user = array_only((array) json_decode($value, true), array_keys(static::$preferences));
     return array_merge($defaults, $user);
 }
Example #10
0
function db_query_indexed($index, $sql, $params = array())
{
    $res = db_query($sql, $params);
    return array_build($res, function ($i, $data) use($index) {
        return array($data[$index], $data);
    });
}
Example #11
0
 /**
  * Applies a filter scope constraints to a DB query.
  * @param  string $scope
  * @param  Builder $query
  * @return Builder
  */
 public function applyScopeToQuery($scope, $query)
 {
     if (is_string($scope)) {
         $scope = $this->getScope($scope);
     }
     if (!$scope->value) {
         return;
     }
     $value = is_array($scope->value) ? array_keys($scope->value) : $scope->value;
     /*
      * Condition
      */
     if ($scopeConditions = $scope->conditions) {
         if (is_array($value)) {
             $filtered = implode(',', array_build($value, function ($key, $_value) {
                 return [$key, Db::getPdo()->quote($_value)];
             }));
         } else {
             $filtered = Db::getPdo()->quote($value);
         }
         $query->whereRaw(strtr($scopeConditions, [':filtered' => $filtered]));
     }
     /*
      * Scope
      */
     if ($scopeMethod = $scope->scope) {
         $query->{$scopeMethod}($value);
     }
     return $query;
 }
Example #12
0
 /**
  * Parse string into an array of method names and argument lists.
  *
  * For example
  *   "where(id|name, =, *)"
  * becomes
  *   [
  *      "where" => ["id|name", "=", "*"]
  *   ]
  *
  * @param string $input
  * @return array
  */
 protected function parseStringToArray($input)
 {
     return array_build(preg_split('#(?<=\\))\\s*(?=[a-z])#i', $input), function ($index, $rule) {
         if (!preg_match('#^(?<method>[a-z]+)\\((?<args>[^)]*)\\)$#i', $rule, $clause)) {
             throw new InvalidArgumentException('Could not parse rule [' . $rule . ']');
         }
         return [$clause['method'], preg_split('#\\s*,\\s*#', $clause['args'])];
     });
 }
Example #13
0
 /**
  * Looks up and translates a message by its string.
  * @param  string $messageId
  * @param  array  $params
  * @return string
  */
 public static function trans($messageId, $params)
 {
     $msg = static::get($messageId);
     $params = array_build($params, function ($key, $value) {
         return [':' . $key, $value];
     });
     $msg = strtr($msg, $params);
     return $msg;
 }
Example #14
0
 /**
  * Applies a filter scope constraints to a DB query.
  * @param  string $scope
  * @param  Builder $query
  * @return Builder
  */
 public function applyScopeToQuery($scope, $query)
 {
     if (is_string($scope)) {
         $scope = $this->getScope($scope);
     }
     if (!$scope->value) {
         return;
     }
     switch ($scope->type) {
         case 'string':
             if ($scope->value && is_scalar($scope->value) && trim($scope->value)) {
                 if (array_get($scope->config, 'isNumericFindId') && is_numeric(trim($scope->value))) {
                     $query->where('id', trim($scope->value));
                 } else {
                     $query->searchWhere($scope->value, array_get($scope->config, 'fields') ?: [$scope->scopeName]);
                 }
             }
             break;
         case 'date':
         case 'range':
             $this->applyDateScopeToQuery($scope, $query);
             break;
         default:
             $value = is_array($scope->value) ? array_keys($scope->value) : $scope->value;
             /*
              * Condition
              */
             if ($scopeConditions = $scope->conditions) {
                 foreach ((array) $scopeConditions as $scopeKey => $scopeCondition) {
                     if (is_array($scopeConditions)) {
                         if (array_key_exists($scopeKey, $scope->value) == false) {
                             continue;
                         }
                     }
                     if (is_array($value)) {
                         $filtered = implode(',', array_build($value, function ($key, $_value) {
                             return [$key, Db::getPdo()->quote($_value)];
                         }));
                     } else {
                         $filtered = Db::getPdo()->quote($value);
                     }
                     $query->whereRaw(strtr($scopeCondition, [':filtered' => $filtered]));
                 }
             }
     }
     /*
      * Scope
      */
     if ($scopeMethod = $scope->scope) {
         $query->{$scopeMethod}($value);
     }
     return $query;
 }
Example #15
0
 protected function errors($validate, $errors)
 {
     if ($validate && $errors) {
         return implode(PHP_EOL, array_build($errors, function ($key, $val) {
             return [$key, $this->_render('error', $val)];
         }));
     }
     return '';
 }
Example #16
0
function BenchmarkXarrayBuild(Benchmark $b)
{
    $arr = makeUserArray(ARRSIZE);
    $b->resetTimer();
    for ($i = 0; $i < $b->N(); $i++) {
        array_build($arr, function ($k, $v) {
            return array($v["uid"], $v);
        });
    }
}
 public function __construct($items = array(), $filters = 0)
 {
     parent::__construct($items);
     $this->filters = $filters;
     $this->filters_closures = [self::SENSITIVE => function ($k, $v, $filters) {
         $sensitive = $v instanceof Parameter ? $v->sensitive : data_get($v, 'sensitive');
         return $sensitive ? [$k, $v] : null;
     }, self::INSENSITIVE => function ($k, $v, $filters) {
         $sensitive = $v instanceof Parameter ? $v->sensitive : data_get($v, 'sensitive');
         return $sensitive ? null : [$k, $v];
     }, self::MASK_SENSITIVE => function ($k, $v, $filters) {
         $sensitive = $v instanceof Parameter ? $v->sensitive : data_get($v, 'sensitive');
         $value = $v instanceof Parameter ? $v->value : data_get($v, 'value');
         if ($value and $sensitive) {
             if ($v instanceof Parameter) {
                 $v = clone $v;
                 $v->value = '*****';
             } else {
                 array_set($v, 'value', '*****');
             }
         }
         return [$k, $v];
     }, self::FLAT => function ($k, $v, $filters) {
         if ($v instanceof Parameter) {
             $v = $v->get('value');
         }
         if (is_array($v)) {
             $flat = array_build(array_dot($v), function ($kk, $vv) use($k, $filters) {
                 array_forget($filters, [self::SENSITIVE, self::INSENSITIVE]);
                 return static::filterKeyValue(str_replace('.', '_', "{$k}.{$kk}"), $vv, $filters);
             });
             return [null, value($flat)];
         }
         return [$k, $v];
     }, self::STUDLY => function ($k, $v, $filters) {
         return [studly_case($k), $v];
     }, self::SNAKE => function ($k, $v, $filters) {
         return [snake_case($k), $v];
     }, self::DECRYPTED => function ($k, $v, $filters) {
         if (is_array($v)) {
             $dot = array_dot($v);
             $dot_decrypted = array_map(function ($v) {
                 try {
                     $v = Crypt::decrypt($v);
                 } catch (DecryptException $e) {
                 }
                 return $v;
             }, $dot);
             foreach ($dot_decrypted as $key => $decrypted_value) {
                 array_set($v, $key, $decrypted_value);
             }
         }
         if (is_string($v)) {
             try {
                 $v = Crypt::decrypt($v);
             } catch (DecryptException $e) {
             }
         }
         return [$k, $v];
     }, self::NO_METADATA => function ($k, $v, $filters) {
         return array_has(array_flip(['ui', 'status']), $k) ? null : [$k, $v];
     }, self::DEFINED => function ($k, $v, $filters) {
         return is_null($v) ? null : [$k, $v];
     }];
 }
Example #18
0
 /**
  * Applies a filter scope constraints to a DB query.
  * @param  string $scope
  * @param  Builder $query
  * @return Builder
  */
 public function applyScopeToQuery($scope, $query)
 {
     if (is_string($scope)) {
         $scope = $this->getScope($scope);
     }
     if (!$scope->value) {
         return;
     }
     switch ($scope->type) {
         case 'date':
             if ($scope->value instanceof Carbon) {
                 $value = $scope->value;
                 /*
                  * Condition
                  */
                 if ($scopeConditions = $scope->conditions) {
                     $query->whereRaw(DbDongle::parse(strtr($scopeConditions, [':filtered' => $value->format('Y-m-d'), ':after' => $value->format('Y-m-d H:i:s'), ':before' => $value->copy()->addDay()->addMinutes(-1)->format('Y-m-d H:i:s')])));
                 } elseif ($scopeMethod = $scope->scope) {
                     $query->{$scopeMethod}($value);
                 }
             }
             break;
         case 'daterange':
             if (is_array($scope->value) && count($scope->value) > 1) {
                 list($after, $before) = array_values($scope->value);
                 if ($after && $after instanceof Carbon && $before && $before instanceof Carbon) {
                     /*
                      * Condition
                      */
                     if ($scopeConditions = $scope->conditions) {
                         $query->whereRaw(DbDongle::parse(strtr($scopeConditions, [':afterDate' => $after->format('Y-m-d'), ':after' => $after->format('Y-m-d H:i:s'), ':beforeDate' => $before->format('Y-m-d'), ':before' => $before->format('Y-m-d H:i:s')])));
                     } elseif ($scopeMethod = $scope->scope) {
                         $query->{$scopeMethod}($after, $before);
                     }
                 }
             }
             break;
         default:
             $value = is_array($scope->value) ? array_keys($scope->value) : $scope->value;
             /*
              * Condition
              */
             if ($scopeConditions = $scope->conditions) {
                 /*
                  * Switch scope: multiple conditions, value either 1 or 2
                  */
                 if (is_array($scopeConditions)) {
                     $conditionNum = is_array($value) ? 0 : $value - 1;
                     list($scopeConditions) = array_slice($scopeConditions, $conditionNum);
                 }
                 if (is_array($value)) {
                     $filtered = implode(',', array_build($value, function ($key, $_value) {
                         return [$key, Db::getPdo()->quote($_value)];
                     }));
                 } else {
                     $filtered = Db::getPdo()->quote($value);
                 }
                 $query->whereRaw(DbDongle::parse(strtr($scopeConditions, [':filtered' => $filtered])));
             } elseif ($scopeMethod = $scope->scope) {
                 $query->{$scopeMethod}($value);
             }
             break;
     }
     return $query;
 }
Example #19
0
 protected function getSupportedLocales()
 {
     return array_build(File::directories(__DIR__ . '/../../lang'), function ($k, $d) {
         return array($k, basename($d));
     });
 }
Example #20
0
 /**
  * Parse the given filter string.
  *
  * @param  string  $filters
  * @return array
  */
 protected function parseFilters($filters)
 {
     return array_build(static::explodeFilters($filters), function ($key, $value) {
         return static::parseFilter($value);
     });
 }