public function distributeResources($resources, $componentPrefixedKey = 'LogicalResourceId') { Log::debug(__METHOD__ . ' start'); $groupedResourceCollection = []; foreach ($this->items as $componentKey => $component) { foreach ($resources as $resourceKey => $resource) { if (Stringy::create($resource[$componentPrefixedKey])->startsWith(studly_case($componentKey), false)) { $groupedResourceCollection[$componentKey][] = $resource; unset($resources[$resourceKey]); } if ($resource[$componentPrefixedKey] == data_get($resource, 'StackName') or $resource[$componentPrefixedKey] == '') { $groupedResourceCollection['_stack'][] = $resource; unset($resources[$resourceKey]); } } } if (count($resources) > 0) { $groupedResourceCollection['_ungrouped'] = $resources; } $groupedResourceCollectionKeys = array_keys($groupedResourceCollection); $retval = Collection::make($groupedResourceCollection)->map(function ($resources) { return Collection::make($resources); })->replaceKeys(function ($k) use($groupedResourceCollectionKeys) { return $groupedResourceCollectionKeys[$k]; }); Log::debug(__METHOD__ . ' end'); return $retval; }
/** * Grabs the debug back trace, removes the call to this method and returns a cleaned up array of the trace * * @param bool|true $clean If true, trace is cleaned such that "call" will reflect the combination of "file", * "class", "line", and "type" * @param int $options Options for debug_backtrace() * @param int $limit The maximum steps to backtrace (defaults to zero, or no limit) * * @return array */ public static function backtrace($clean = true, $options = DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit = 0) { $_originalTrace = debug_backtrace($options, $limit); // Remove this call... array_shift($_originalTrace); $_cleanTrace = []; if ($clean) { foreach ($_originalTrace as $_step) { $_args = data_get($_step, 'args', []); $_class = data_get($_step, 'class'); $_file = data_get($_step, 'file'); $_line = data_get($_step, 'line'); $_function = data_get($_step, 'function'); $_type = data_get($_step, 'type'); $_object = data_get($_step, 'object'); // Clean up some values first... '{closure}' == substr($_function, -9) && ($_function = '{closure}'); !empty($_line) && ($_line = '@' . $_line); // Object method invoked? if ($_class && $_type && $_function) { $_entry = ['call' => $_class . $_type . $_function . $_line]; } else { $_entry = ['call' => $_file . '::' . $_function . $_line]; } $_entry['args'] = json_encode($_args, JSON_UNESCAPED_SLASHES); $_entry['object'] = json_encode($_object ?: new \stdClass(), JSON_UNESCAPED_SLASHES); $_cleanTrace[] = $_entry; } } return $clean ? $_cleanTrace : $_originalTrace; }
/** * Format a date/time column. * * @param string $column * @param string $format * @param string $timezone * @return null|string */ protected function __carbon($column, $format, $timezone = null) { if (!isset($timezone)) { $timezone = config('app.timezone.display', 'UTC'); } $dt = data_get($this->model, $column); if ($dt instanceof Carbon) { $dt->setTimezone($timezone); switch ($format) { // Dec 25, 1975 case 'date': return $dt->toFormattedDateString(); // Dec 25, 1975 2:15 PM // Dec 25, 1975 2:15 PM case 'time': return $dt->format('g:i A'); // Thu, Dec 25, 1975 2:15 PM // Thu, Dec 25, 1975 2:15 PM case 'datetime': return implode(' ', [$dt->toFormattedDateString(), $dt->format('g:i A')]); } return $dt->format($format); } return null; }
/** * @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); }
/** * Magic Getter. * * @param string $property Accessed property name * * @return mixed */ public function __get($property) { if (!is_null($aliased = $this->aliasGet($property))) { return $aliased; } return data_get($this->object, $property); }
/** * Modules of installed or not installed. * * @param bool $installed * * @return \Illuminate\Support\Collection */ public function getModules($installed = false) { if ($this->modules->isEmpty()) { if ($this->files->isDirectory($this->getModulePath()) && !empty($directories = $this->files->directories($this->getModulePath()))) { (new Collection($directories))->each(function ($directory) use($installed) { if ($this->files->exists($file = $directory . DIRECTORY_SEPARATOR . 'composer.json')) { $package = new Collection(json_decode($this->files->get($file), true)); if (Arr::get($package, 'type') == 'notadd-module' && ($name = Arr::get($package, 'name'))) { $module = new Module($name); $module->setAuthor(Arr::get($package, 'authors')); $module->setDescription(Arr::get($package, 'description')); if ($installed) { $module->setInstalled($installed); } if ($entries = data_get($package, 'autoload.psr-4')) { foreach ($entries as $namespace => $entry) { $module->setEntry($namespace . 'ModuleServiceProvider'); } } $this->modules->put($directory, $module); } } }); } } return $this->modules; }
/** * @param $verb * @param $endpoint * @param array $options * @param callable|null $successCallback * @param callable|null $failureCallback * @param null $name * @return PromiseInterface */ public function clientCallAsync($verb, $endpoint, $options = [], callable $successCallback = null, callable $failureCallback = null, $name = null) { if ($name === null) { list(, $caller) = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); $name = $caller['function']; } $ref = $this->getNextReference(); $this->startLog($ref, $endpoint, $verb, $name, data_get($options, 'json', data_get($options, 'body'))); return $this->pending[$name][$ref] = $this->connection->{"{$verb}Async"}($endpoint, $options + ['query' => $this->getQuery(), 'headers' => $this->getHeaders()])->then(function ($response) use($name, $ref, $successCallback) { $this->endLog($ref, $response); unset($this->pending[$name][$ref]); if ($successCallback !== null) { return $successCallback($response); } return $response; }, function ($exception) use($name, $ref, $failureCallback) { $response = $exception->getResponse(); $this->endLog($ref, $response); unset($this->pending[$name][$ref]); if ($failureCallback !== null) { return $failureCallback($exception); } return null; }); }
/** * Evaluate a target entity with arguments. * * @param $target * @param array $arguments * @return mixed */ public function evaluate($target, array $arguments = []) { /** * If the target is an instance of Closure then * call through the IoC it with the arguments. */ if ($target instanceof \Closure) { return $this->container->call($target, $arguments); } /** * If the target is an array then evaluate * each of it's values. */ if (is_array($target)) { foreach ($target as &$value) { $value = $this->evaluate($value, $arguments); } } /** * if the target is a string and is in a traversable * format then traverse the target using the arguments. */ if (is_string($target) && !isset($arguments[$target]) && $this->isTraversable($target)) { $target = data_get($arguments, $target, $target); } return $target; }
public function getIsAdministerAttribute() { $roles = ['super', 'admin']; return $this->roles->filter(function ($item) use($roles) { return in_array(data_get($item, 'role'), $roles); })->count() > 0; }
/** * Process the data and make necessary changes * e.g. create JSON strings from * * @param string $key * @param string|array|null $default * @return string|array */ public function input($key = null, $default = null) { $input = request()->input(); if (!empty($input['savedSearches']) && is_array($input['savedSearches'])) { $input['savedSearches'] = json_encode($input['savedSearches']); } return data_get($input, $key, $default); }
public function getOptions($key) { if ($this->settings[$key]['type'] == 'checkbox') { return [true, false]; } $options = data_get($this->settings[$key], 'options', []); return value($options); }
public function testInvalidExerciseIsNotUpdated() { $this->artisan('db:seed'); $exercise = app('db')->table('exercises')->whereId(1)->first(); $otherExercise = ["name" => data_get($exercise, "name"), "id" => 2]; $this->put('__api/exercises/2', $otherExercise, ['HTTP_X-Requested-With' => 'XMLHttpRequest']); $this->assertResponseStatus(422); $this->notSeeInDatabase('exercises', $otherExercise); }
/** * Get the application namespace from the Composer file. * * @return string * * @throws \RuntimeException */ protected function getAppNamespace() { $composer = (array) json_decode(file_get_contents(base_path() . '/composer.json', true)); foreach ((array) data_get($composer, 'autoload.psr-4') as $namespace => $path) { if (realpath(app_path()) == realpath(base_path() . '/' . $path)) { return $namespace; } } throw new \RuntimeException("Unable to detect application namespace."); }
/** * 获取配置 * * @param string $name 配置项名 * @param string $default 默认值,配置选项不存在的话默认值将会被指定并返回 * * @return mixed * * @author AlpFish 2016/7/25 15:40 */ public function get($name = null, $default = null) { if (is_string($name)) { if (!data_get(self::$data, $name, $default)) { $this->seachLoad($name); } return data_get(self::$data, $name, $default); } return self::$data; }
/** * @param int|object|array|Model $mixed * @return Model */ protected function getParentModel($mixed) { if ($mixed instanceof Model == false) { if (is_numeric($mixed) == false) { $mixed = data_get($mixed, 'id'); } return $this->parentModel->newInstance(['id' => $mixed], true); } return $mixed; }
/** * @param array $ids * @return static */ public function sortByIds(array $ids) { $ids = array_flip($ids); return $this->sort(function ($a, $b) use($ids) { if ($a instanceof BaseModel && $b instanceof BaseModel) { return $ids[$a->getKey()] - $ids[$b->getKey()]; } else { return $ids[data_get($a, 'id')] - $ids[data_get($b, 'id')]; } }); }
public function getUser() { if ($this->subtype == 'bot_message') { return $this->username; } if ($this->user == 'USLACKBOT') { return 'slackbot'; } $user = User::where('sid', $this->user)->first(); return data_get($user, 'name', $this->username); }
/** * Get the payload for the given event. * * @param mixed $event * @return array */ protected function getPayloadFromEvent($event) { if (method_exists($event, 'broadcastWith')) { return array_merge($event->broadcastWith(), ['socket' => data_get($event, 'socket')]); } $payload = []; foreach ((new ReflectionClass($event))->getProperties(ReflectionProperty::IS_PUBLIC) as $property) { $payload[$property->getName()] = $this->formatProperty($property->getValue($event)); } return $payload; }
/** * @throws \RuntimeException */ private function setNamespace() { $composer = json_decode(file_get_contents($this->laravel->basePath() . '/composer.json'), true); foreach ((array) data_get($composer, 'autoload.psr-4') as $namespace => $path) { foreach ((array) $path as $pathChoice) { if (realpath($this->laravel->basePath() . DIRECTORY_SEPARATOR . 'app') == realpath($this->laravel->basePath() . '/' . $pathChoice)) { return $this->namespace = $namespace . $this->name; } } } throw new RuntimeException('Unable to detect application namespace.'); }
public function forUser(User $user, $year) { $start = Carbon::createFromDate($year, 1, 1); $end = Carbon::createFromDate($year + 1, 1, 1); $data = DB::table('reminders')->where('starts_on', '>=', $start->toDateString())->where('starts_on', '<', $end->toDateString())->where('user_id', auth_user()->id)->groupBy('month')->orderBy('month')->get([DB::raw('MONTH(starts_on) AS month'), DB::raw('COUNT(*) AS count')]); $data = array_pluck($data, 'count', 'month'); $result = []; for ($i = 0; $i < 12; $i++) { $result[] = (int) data_get($data, $i + 1, 0); } return $result; }
/** * Identical to the 5.3 implementation of contains */ public function contains($key, $value = null) { if (func_num_args() == 2) { return $this->contains(function ($item) use($key, $value) { return data_get($item, $key) == $value; }); } if ($this->useAsCallable($key)) { return !is_null($this->first($key)); } return in_array($key, $this->items); }
public function getURLTitle() { $url = request('url'); $data = OEmbed::getData($url); $title = data_get($data, 'meta.title', ''); $title = str_limit($title, 128); $description = data_get($data, 'meta.description', ''); $description = str_limit($description, 255); // Find duplicates $duplicates = Content::where('url', $url)->get(['title', 'group_id'])->toArray(); return ['status' => 'ok', 'title' => $title, 'description' => $description, 'duplicates' => $duplicates]; }
function tagtpl_cache() { $relatedtag = unserialize(data_get('relatedtag')); if(empty($relatedtag)) $relatedtag = array(); foreach($relatedtag['data'] as $appid => $data) { $relatedtag['limit'][$appid] = empty($relatedtag['limit'][$appid])?0:intval($relatedtag['limit'][$appid]); $data['template'] = trim($data['template']); if(empty($relatedtag['limit'][$appid]) || empty($data['template'])) { unset($relatedtag['data'][$appid]); unset($relatedtag['limit'][$appid]); } } cache_write('tagtpl', "_SGLOBAL['tagtpl']", $relatedtag); }
/** * Find all models with optional criteria. * * @param array $criteria * @return object|array */ public function findAll(array $criteria = []) { if ($criteria) { $this->withCriteria($criteria); } if ($this->pagination) { $result = $this->query()->paginate(data_get($this->pagination, 'perPage'), $this->getColumns(), data_get($this->pagination, 'pageName'), data_get($this->pagination, 'page')); } else { $result = $this->query()->get($this->getColumns()); } $this->reset(); return $result; }
/** * Form View Generator for Orchestra\Extension. * * @param \Illuminate\Support\Fluent $model * @param string $name * * @return \Orchestra\Contracts\Html\Form\Builder */ public function configure($model, $name) { return $this->form->of("orchestra.extension: {$name}", function (FormGrid $form) use($model, $name) { $form->setup($this, "orchestra::extensions/{$name}/configure", $model); $handles = data_get($model, 'handles', $this->extension->option($name, 'handles')); $configurable = data_get($model, 'configurable', true); if (!is_null($handles) && $configurable !== false) { $form->fieldset(function (Fieldset $fieldset) use($handles) { // We should only cater for custom URL handles for a route. $fieldset->control('input:text', 'handles')->label(trans('orchestra/foundation::label.extensions.handles'))->value(str_replace(['{{domain}}', '{domain}'], '{domain}', $handles)); }); } }); }
/** * Get form value from the eloquent model. * * @param string $key * * @return mixed */ public function getFormValue($key) { $value = $this->getAttributeFromArray($key); if (in_array($key, $this->getDates()) && !is_null($value)) { $value = $this->asDateTime($value); } if ($this->hasFormMutator($key)) { $value = $this->mutateFormAttribute($key, $value); } else { // No form mutator, let the model resolve this $value = data_get($this, $key); } return $value; }
/** * Get the application namespace. * * @return string * * @throws \RuntimeException */ public function getAppNamespace() { if (!is_null($this->namespace)) { return $this->namespace; } $composer = json_decode(file_get_contents(base_path() . '/composer.json'), true); foreach ((array) data_get($composer, 'autoload.psr-4') as $namespace => $path) { foreach ((array) $path as $pathChoice) { if (realpath(app('path')) == realpath(base_path() . '/' . $pathChoice)) { return $this->namespace = $namespace; } } } throw new RuntimeException('Unable to detect application namespace.'); }
/** * 从给定的数组中提取出键/值对 * * @param \ArrayAccess|array $array * @param string|array $value * @param string|array|null $key * @return array */ public static function pluck($array, $value, $key = null) { $results = []; list($value, $key) = static::explodePluckParameters($value, $key); foreach ($array as $item) { $itemValue = data_get($item, $value); if (is_null($key)) { $results[] = $itemValue; } else { $itemKey = data_get($item, $key); $results[$itemKey] = $itemValue; } } return $results; }
protected function processData($data) { if (array_key_exists('html', $data)) { return $data['html']; } foreach ($data['links'] as $link) { $rel = data_get($link, 'rel', []); if (in_array('file', $rel)) { return $this->embedMedia($link); } if (in_array('image', $rel)) { return $this->embedImage($link['href']); } } return false; }
/** * Form View Generator for Orchestra\Extension. * * @param \Illuminate\Support\Fluent $model * @param string $name * * @return \Orchestra\Contracts\Html\Form\Builder */ public function configure($model, $name) { return $this->form->of("orchestra.extension: {$name}", function (FormGrid $form) use($model, $name) { $form->setup($this, "orchestra::extensions/{$name}/configure", $model); $handles = data_get($model, 'handles', $this->extension->option($name, 'handles')); $configurable = data_get($model, 'configurable', true); $form->fieldset(function (Fieldset $fieldset) use($handles, $name, $configurable) { // We should only cater for custom URL handles for a route. if (!is_null($handles) && $configurable !== false) { $fieldset->control('input:text', 'handles')->label(trans('orchestra/foundation::label.extensions.handles'))->value($handles); } $fieldset->control('input:text', 'migrate')->label(trans('orchestra/foundation::label.extensions.update'))->field(function () use($name) { return app('html')->link(handles("orchestra::extensions/{$name}/update", ['csrf' => true]), trans('orchestra/foundation::label.extensions.actions.update'), ['class' => 'btn btn-info']); }); }); }); }