public function getInitial() { $words = new Collection(explode(' ', $this->name)); // if name contains single word, use first N character if ($words->count() === 1) { if ($this->name->length() >= $this->length) { return $this->name->substr(0, $this->length); } return (string) $words->first(); } // otherwise, use initial char from each word $initials = new Collection(); $words->each(function ($word) use($initials) { $initials->push(Stringy::create($word)->substr(0, 1)); }); return $initials->slice(0, $this->length)->implode(''); }
public function summary(Request $request, $regionId) { $region = Region::find($regionId); $user = false; $token = $request->header('Authorization'); if ($token) { if (isset($token[1])) { $token = explode(' ', $request->header('Authorization'))[1]; $payload = (array) JWT::decode($token, Config::get('app.token_secret'), array('HS256')); $user = User::find($payload['sub']); } } $participants = new Collection(); $past_competitions = new Collection(); $next_competitions = new Collection(); $next_competition = array(); $competitions = array(); if ($regionId == 1) { $competitions = Competition::all(); $videos = DB::table('medias')->where('region_id', '<>', $region->id)->get(); $region->competitions = $competitions; } else { $competitions = $region->competitions; $videos = DB::table('medias')->where('region_id', '=', $region->id)->get(); } $competitions->each(function ($competition) use($past_competitions, $next_competitions, $participants, $user) { $competition->users->each(function ($participant) use($participants, $competition, $user) { if ($user && $user->id == $participant->id) { $competition->already_participating = true; } $participant->medias; $participant->competitions; $participants->push($participant); }); $competition->location; $competition->videos; if (Carbon::now()->gte($competition->event_date)) { $competition->past = true; $past_competitions->push($competition); } else { $competition->past = false; $next_competitions->push($competition); } }); $region->next_competition = $next_competitions->first(); $region->next_competitions = $next_competitions; $region->past_competitions = $past_competitions; $region->videos = $videos; $region->videos_count = count($videos); $region->competitions_count = count($competitions); $region->participants = $participants->unique(); $region->participants_count = count($region->participants); return $region; }
/** * @return \Pipboy\Contracts\AbstractWeapon */ public function getFirstWeapon() { if (is_null($this->items)) { return false; } return $this->items->first(function ($i, AbstractItem $item) { return !(strpos($item->getuid(), 'weapon') === false); }); }
/** * @param Collection $entries * * @return array */ public function multiYear(Collection $entries) { // dataset: $data = ['count' => 0, 'labels' => [], 'datasets' => []]; // get labels from one of the categories (assuming there's at least one): $first = $entries->first(); $keys = array_keys($first['spent']); foreach ($keys as $year) { $data['labels'][] = strval($year); } // then, loop all entries and create datasets: foreach ($entries as $entry) { $name = $entry['name']; $spent = $entry['spent']; $earned = $entry['earned']; if (array_sum(array_values($spent)) != 0) { $data['datasets'][] = ['label' => 'Spent in category ' . $name, 'data' => array_values($spent)]; } if (array_sum(array_values($earned)) != 0) { $data['datasets'][] = ['label' => 'Earned in category ' . $name, 'data' => array_values($earned)]; } } $data['count'] = count($data['datasets']); return $data; }
/** * Determines a winner from the list of buzzes accumulated. * * Note: This method is destructive, and will clear the list of buzzes on completion. * @return BuzzerResolution */ public function resolve() { if ($this->isEmpty()) { return BuzzerResolution::createFailure(); } /** @var BuzzReceivedEvent $winner */ $winner = $this->buzzes->reduce(function (BuzzReceivedEvent $carry, BuzzReceivedEvent $event) { if ($event->getDifference() < $carry->getDifference()) { return $event; } return $carry; }, $this->buzzes->first()); $resolution = BuzzerResolution::createSuccess($winner->getContestant(), $winner->getDifference()); $this->buzzes = new Collection(); return $resolution; }
/** * @param Collection $collection * @param $request */ public function __construct(Collection $collection, $request) { $this->collection = $collection; $this->original_collection = $collection; $this->columns = array_keys($this->serialize((array) $collection->first())); parent::__construct($request); }
/** * @param Collection $collection * @param \Yajra\Datatables\Request $request */ public function __construct(Collection $collection, Request $request) { $this->request = $request; $this->collection = $collection; $this->original_collection = $collection; $this->columns = array_keys($this->serialize($collection->first())); }
public static function makeForCollection(Collection $collection) { if ($collection->count() === 0) { throw new \OutOfRangeException("Requested collection does not contain any items"); } return static::makeForModel($collection->first()); }
protected function collectPermissions($permission) { if (is_string($permission)) { $permission = app(PermissionContract::class)->whereSlug($permission)->first(); } if (is_array($permission) or $permission instanceof Collection) { $permission = new Collection($permission); if (is_string($permission->first())) { return app(PermissionContract::class)->whereIn('slug', $permission->toArray())->get(); } elseif ($permission->first() instanceof PermissionContract) { return $permission; } } elseif ($permission instanceof PermissionContract) { return $permission; } return null; }
/** * @param $properties * @param $content */ private function handleDirectory(Collection $properties, $content) { $properties->push($content['filename']); $this->filesystem->createDir('Api/' . $this->endpoint->first()); $generator = new EndpointGenerator($this->inputInterface, $this->out, $this->dialogHelper); $endpoint = str_replace("Request/", "", $content['path']); $generator->generateForEndpoint($endpoint); }
/** * @param Collection $schedules * @return \Filmoteca\Models\Activity */ public function single(Collection $schedules) { $activity = new Activity(); $firstSchedule = $schedules->first(); $film = $firstSchedule->exhibition->exhibition_film->film; $auditorium = $firstSchedule->auditorium; $activity->setId($film->id . $auditorium->id)->setTitle($firstSchedule->exhibition->exhibition_film->title)->setFacility($auditorium)->setPublicType('General')->setContact(self::getContact($firstSchedule))->setSchedules(Formatter::toDateTime($schedules))->setExtraSchedules(Formatter::toExtraTime($schedules))->setPrices(Formatter::toPrices($schedules))->setDiscounts(Formatter::toDiscounts($schedules))->setCommentaries($firstSchedule->exhibition->notes)->setCategory(self::CATEGORY)->setImage($film->image)->setReview($firstSchedule->exhibition->exhibition_film->film->synopsis); return $activity; }
/** * Get the instance as an array. * * @return array */ public function toArray() { if ($this->channels instanceof Collection) { // 先拿到第一个子级频道项,并拿到它的父级频道ID // 开始遍历整个频道栏目,但是跳过第一条记录 // 当然,每当遇到父级频道ID与当前频道ID相同 // 则该为根级频道,一次搜索完成 $first = $this->channels->first(); $cursor = $first->channel_id; $iterator = $this->channels->getIterator(); while ($iterator->valid() && ($channel = $iterator->current())) { echo 'prepare' . PHP_EOL; if ($channel->channel_id == $cursor || $channel->flag === 1) { $iterator->next(); continue; } echo 'start' . PHP_EOL; var_dump($first->channel_id, $first->channel_parent); // 当一次搜索完成时,重新搜索数据集 if (isset($_parent) && $_parent->channel_id === $_parent->channel_parent) { echo 'rewind' . PHP_EOL; $iterator->rewind(); continue; } if ($channel->channel_id === $first->channel_parent) { $_parent = $channel; echo 'merge' . PHP_EOL; var_dump($_parent->channel_id); $this->{$_parent->channel_type}[$_parent->channel_name] = array_merge($this->{$_parent->channel_type}, ['data' => $first, 'idx' => $cursor, 'to' => $_parent->channel_id]); echo 'to wind' . PHP_EOL; var_dump($this->{$_parent->channel_type}); // 因为已经设置过子父级关系,则当前数据项设置为1 $cursor = $_parent->channel_id; $first = $_parent; $channel->flag = 1; } echo 'complete' . PHP_EOL; $iterator->next(); } } return array_merge(['default' => $this->default], ['mega' => $this->mega]); }
public function getUserTrends(Collection $rounds) { $first = $rounds->first(); $last = $rounds->last(); $totalRounds = $rounds->count(); $strokes = ($last->totalStrokes() - $first->totalStrokes()) / $totalRounds; $putts = ($last->totalPutts() - $first->totalPutts()) / $totalRounds; $strokesPar3 = ($last->totalStrokesPar(3) - $first->totalStrokesPar(3)) / $totalRounds; $strokesPar4 = ($last->totalStrokesPar(4) - $first->totalStrokesPar(4)) / $totalRounds; $strokesPar5 = ($last->totalStrokesPar(5) - $first->totalStrokesPar(5)) / $totalRounds; return compact('strokes', 'putts', 'strokesPar3', 'strokesPar4', 'strokesPar5'); }
/** * Gets meta data * * @return Illuminate\Support\Collection */ public function getMeta($key, $getObj = false) { $meta = $this->meta()->where('key', $key)->get(); if ($getObj) { $collection = $meta; } else { $collection = new Collection(); foreach ($meta as $m) { $collection->put($m->id, $m->value); } } return $collection->count() <= 1 ? $collection->first() : $collection; }
/** * @param \Illuminate\Support\Collection $collection * @param array $attributes * * @return bool|int|\WP_Error */ public static function update(Collection $collection, $attributes = []) { $user = $collection->first(); $attr = ['ID' => $user->ID]; $self = new static(); $attributes = $self->prepareFields($attributes, 'updating'); $user_id = wp_update_user(array_merge($attributes, $attr)); if (is_wp_error($user_id)) { return $user_id; } $self->addOrUpdateMetafields($user->ID, $attributes); return true; }
/** * Gets the first question that matches both the category and value. * @param $categoryName * @param int $value * @return Question * @throws QuestionNotFoundException */ public function getQuestionByCategoryAndValue($categoryName, $value) : Question { /** @var Category $category */ $category = $this->categories->first(function (Category $category) use($categoryName) { return $category->getName() === $categoryName; }); if ($category === null) { throw new QuestionNotFoundException(); } $question = $category->getQuestions()->first(function (Question $question) use($value) { return $question->getValue() === $value; }); if ($question === null) { throw new QuestionNotFoundException(); } return $question; }
/** * 取得 集合中 满足 闭包条件的 第一个元素 first * 首先 call Collection 的 first method * first method call Arr::first($this->items, $callback, $default); * 它返回的是一个值 * * 对应的 * 取得 集合中 满足 闭包条件的 最后一个元素 last */ public function first() { debug($this->collection); //返回第一个满足条件的 $value $first = $this->collection->first(function ($key, $value) { return $value['price'] == 100; }); debug($first); $last = $this->collection->last(function ($key, $value) { return $value['price'] == 100; }); debug($last); //这里就直接返回第一个集合元素 $first = $this->collection->first(); debug($first); return view('index'); }
/** * Gets meta data * * @param $key * @param null $default * @param bool $getObj * @return Collection */ public function getMeta($key, $default = null, $getObj = false) { $meta = $this->meta()->where('key', $key)->get(); if ($getObj) { $collection = $meta; } else { $collection = new Collection(); foreach ($meta as $m) { $collection->put($m->id, $m->value); } } // Were there no records? Return NULL if no default provided if (0 == $collection->count()) { return $default; } return $collection->count() <= 1 ? $collection->first() : $collection; }
/** * Gets the first question that matches both the category and value. * @param $categoryName * @param int $value * @return Question * @throws QuestionNotFoundException */ public function getQuestionByCategoryAndValue($categoryName, $value) { //TODO what if we can't find anything? what if either of these return empty. Must throw exceptions, I suppose. /** @var Category $category */ $category = $this->categories->first(function ($key, Category $category) use($categoryName) { return $category->getName() == $categoryName; }); if ($category == null) { throw new QuestionNotFoundException(); } $question = $category->getQuestions()->first(function ($key, Question $question) use($value) { return $question->getValue() == $value; }); if ($question == null) { throw new QuestionNotFoundException(); } return $question; }
/** * Show the form for creating a new resource. * * @return Response */ public function create() { $user = User::find(\Auth::user()->id); if ($user) { $pengirim = $user->konsumen->idkonsumen; //$pelanggan = quote::select('idpenerima')->where('idkonsumen','=',$pengirim)->get(); $pelanggan = pengirim_penerima::select('penerima AS idpenerima')->where('pengirim', '=', $pengirim)->get(); $penerima = new Collection(); $arr = [0 => '-- Kosongkan pilihan ini untuk penerima baru / belum tercatat --']; foreach ($pelanggan as $p) { $x = konsumen::select('idkonsumen', 'nama', 'cp')->find($p->idpenerima); $arr[$x->idkonsumen] = $x->nama == '-' || $x->nama == '' ? 'Perusahaan / Contact Person: ' . ucfirst($x->cp) : 'Perusahaan: ' . strtoupper($x->nama) . ' (Contact Person: ' . ucfirst($x->cp) . ')'; } $penerima->push($arr); return view('world.dashboard.order-add')->with('pengirim', $pengirim)->with('penerima', $penerima->first()); } else { return view('world.dashboard.order-add')->withErrors('nouser')->with('pengirim', ''); } }
/** * Create recombined array with set fields * * @param Collection $data */ public static function var_set(Collection $data) { $collection = new EloquentCollection(); $model = get_class($data->first()); foreach ($data as $item) { $origin = static::arrayValuesToString($item->getOriginal()); $new = []; foreach ($model::$export_fields as $field => $properties) { if (isset($properties['relation'])) { $method = $properties['relation']['method']; $display = isset($properties['relation']['display']) ? $properties['relation']['display'] : null; $new[] = static::getRelationItems($item, $method, $display); } else { $new[] = $item->{$field}; } } $collection->add($new); } return $collection->toArray(); }
/** * @param Collection $entries * * @return array */ public function multiYear(Collection $entries) : array { // dataset: $data = ['count' => 0, 'labels' => [], 'datasets' => []]; // get labels from one of the budgets (assuming there's at least one): $first = $entries->first(); $keys = array_keys($first['budgeted']); foreach ($keys as $year) { $data['labels'][] = strval($year); } // then, loop all entries and create datasets: foreach ($entries as $entry) { $name = $entry['name']; $spent = $entry['spent']; $budgeted = $entry['budgeted']; $data['datasets'][] = ['label' => 'Spent on ' . $name, 'data' => array_values($spent)]; $data['datasets'][] = ['label' => 'Budgeted for ' . $name, 'data' => array_values($budgeted)]; } $data['count'] = count($data['datasets']); return $data; }
public function summary($centerId) { $center = Center::find($centerId); $members = new Collection(); $past_activities = new Collection(); $next_activities = new Collection(); $next_competition = array(); $activities = array(); if ($centerId == 1) { $activities = Competition::all(); $center->activities = $activities; } else { $activities = $center->activities; } $activities->each(function ($competition) use($past_activities, $next_activities, $members) { $competition->users->each(function ($member) use($members) { $members->push($member); }); $competition->location; if (Carbon::now()->gte($competition->event_date)) { $competition->past = true; $past_activities->push($competition); } else { $competition->past = false; $next_activities->push($competition); } }); Log::info($members); $center->next_competition = $next_activities->first(); $center->next_activities = $next_activities; $center->past_activities = $past_activities; $center->activities_count = count($activities); $center->members = $members->unique(); $center->members_count = count($center->members); return $center; }
/** * Get a registered transformer binding from a collection of items. * * @param \Illuminate\Support\Collection $collection * * @return null|string|callable */ protected function getBindingFromCollection($collection) { return $this->getBinding($collection->first()); }
/** * Generate a downloadable path of multiple songs in zip format. * * @param Collection $songs * * @throws Exception * * @return string */ protected function fromMultipleSongs(Collection $songs) { if ($songs->count() === 1) { return $this->fromSong($songs->first()); } if (!class_exists('ZipArchive')) { throw new Exception('Downloading multiple files requires ZipArchive module.'); } // Start gathering the songs into a zip file. $zip = new ZipArchive(); // We use system's temp dir instead of storage_path() here, so that the generated files // can be cleaned up automatically after server reboot. $filename = rtrim(sys_get_temp_dir(), '/') . '/koel-download-' . uniqid() . '.zip'; if ($zip->open($filename, ZipArchive::CREATE) !== true) { throw new Exception('Cannot create zip file.'); } $localNames = []; $songs->each(function ($s) use($zip, &$localNames) { try { $path = $this->fromSong($s); // We add all files into the zip archive as a flat structure. // As a result, there can be duplicate file names. // The following several lines are to make sure each file name is unique. $name = basename($path); if (array_key_exists($name, $localNames)) { ++$localNames[$name]; $parts = explode('.', $name); $ext = $parts[count($parts) - 1]; $parts[count($parts) - 1] = $localNames[$name] . ".{$ext}"; $name = implode('.', $parts); } else { $localNames[$name] = 1; } $zip->addFile($path, $name); } catch (Exception $e) { Log::error($e); } }); $zip->close(); return $filename; }
/** * Find permission by id * * @param mixed $id * @return array */ public function find($id) { return $this->items->first(function ($key, $value) use($id) { return $value[$this->id] == $id; }); }
public function testFirstWithDefaultAndWithoutCallback() { $data = new Collection(); $result = $data->first(null, 'default'); $this->assertEquals('default', $result); }
/** * @param Collection $rows * * @return $this */ protected function setColumnsToDefault(Collection $rows) { if ($rows->count() == 0) { $columns = ['id' => 'ID']; } else { foreach ($columns = $rows->first()->attributesToArray() as $columnId => &$label) { $label = ucwords(str_replace(['-', '_'], ' ', $columnId)); $label = str_replace('Id', 'ID', $label); } } $this->setColumns($columns); return $this; }
/** * Returns a chart of what has been spent in this period in each category * grouped by month. * * @param CategoryRepositoryInterface $repository * @param $report_type * @param Carbon $start * @param Carbon $end * @param Collection $accounts * * @return \Illuminate\Http\JsonResponse */ public function spentInPeriod(CategoryRepositoryInterface $repository, $report_type, Carbon $start, Carbon $end, Collection $accounts) { $original = clone $start; $cache = new CacheProperties(); // chart properties for cache: $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty($report_type); $cache->addProperty($accounts); $cache->addProperty('category'); $cache->addProperty('spent-in-period'); if ($cache->has()) { return Response::json($cache->get()); // @codeCoverageIgnore } $categories = new Collection(); $sets = new Collection(); $entries = new Collection(); // run a very special query each month: $start = clone $original; while ($start < $end) { $currentEnd = clone $start; $currentStart = clone $start; $currentStart->startOfMonth(); $currentEnd->endOfMonth(); $set = $repository->spentForAccounts($accounts, $currentStart, $currentEnd); $categories = $categories->merge($set); $sets->push([$currentStart, $set]); $start->addMonth(); } $categories = $categories->unique('id'); $categories = $categories->sortBy(function (Category $category) { return $category->name; }); $start = clone $original; while ($start < $end) { $currentEnd = clone $start; $currentStart = clone $start; $currentStart->startOfMonth(); $currentEnd->endOfMonth(); $currentSet = $sets->first(function ($key, $value) use($currentStart) { // set for this date. return $value[0] == $currentStart; }); $row = [clone $currentStart]; /** @var Category $category */ foreach ($categories as $category) { /** @var Category $entry */ $entry = $currentSet[1]->first(function ($key, $value) use($category) { return $value->id == $category->id; }); if (!is_null($entry)) { $row[] = $entry->spent; } else { $row[] = 0; } } $entries->push($row); $start->addMonth(); } $data = $this->generator->spentInPeriod($categories, $entries); $cache->store($data); return $data; }
/** * Get the documents for the specified collection. * * @param \Illuminate\Support\Collection $collection * @return array */ public function getDocumentsForModels(BaseCollection $collection, $fields = null) { if ($collection->isEmpty()) { return []; } $this->validateModelClass($collection->first()); $all = $collection->all(); // Create a dictionary for model collection. $modelIds = array_map(function ($m) { return $m->getIndexKey(); }, $all); $params = $this->getBaseParams(); $params['body']['ids'] = $modelIds; if (!is_null($fields)) { $params['_source'] = $fields; } $results = $this->client->mget($params); $this->checkMultiGetResults($results, $collection); return $results['docs']; }