public function send(Collection $data) { $validator = $this->validator($data->toArray(), $this->type); if (!$validator->fails()) { Mailer::send("emails.{$this->type}", $data->toArray(), function ($message) use($data) { $fromAddress = $data->get('from_address'); $fromName = $data->get('from_name'); $toAddress = $data->get('to_address'); $toName = $data->get('to_name'); $cc = $data->get('cc[]', []); $bcc = $data->get('bcc[]', []); // Send the message $message->from($fromAddress, $fromName); $message->to($toAddress, $toName)->subject($data->get('subject')); foreach ($cc as $address) { $message->cc($address, null); } foreach ($bcc as $address) { $message->bcc($address, null); } }); } else { // Validation failed return ['success' => 0, 'status' => "Failed to validate message", 'messages' => $validator->getMessageBag()->all(), 'data' => $data, 'type' => $this->type]; } if (!count(Mailer::failures())) { $this->sent_at = Carbon::now(); Log::info("Sent {$this->type} email"); return ['success' => 1, 'status' => "successfully sent message", 'data' => $data, 'type' => $this->type]; } Log::info("Failed to send {$this->type} email"); return ['success' => 0, 'status' => "failed to send message", 'messages' => "failed to send message", 'data' => $data, 'type' => $this->type]; }
public static function page($collection, $perPage, $path = '') { //获取分页 的页码 // $currentPage=0; // if(@$_SERVER['REQUEST_URI']){ // $page=explode("=",$_SERVER['REQUEST_URI']); // if(isset($page[1])) { // $currentPage = $page[1]; // } // }else{ // $currentPage=0; // } $page = LengthAwarePaginator::resolveCurrentPage(); $currentPage = $page - 1; $currentPage < 0 ? $currentPage = 0 : ''; // echo $currentPage; //创建一个新的数组集合 $collection = new Collection($collection); //获取分页的数据 $currentPageSearchResults = $collection->slice($currentPage * $perPage, $perPage)->all(); //创建一个新的分页模块 $paginator = new LengthAwarePaginator($currentPageSearchResults, count($collection), $perPage); //获取分页path $url = Request::path(); $path ? $path : $url; //设置分页的path $paginator->setPath($path); return $paginator; }
/** * @param Collection $collection * @return Collection */ public function apply(Collection $collection) { if (!$collection->isEmpty() && !empty($this->criteria)) { foreach ($this->criteria as $key => $parameters) { // Парамментры могут быть пустыми if (empty($parameters)) { continue; } // Фильтруем значение $collection = $collection->filter(function ($value, $k) use($key, $parameters) { foreach ($parameters as $param) { // Получем опреатор в зависимости от ключа $exp = $this->getSign($key); /** @var Parameters $param*/ if (count($param->getAttributes()) === 2) { $attributes = $param->getAttributes(); return eval('return $value->{head($attributes)}' . $exp . ' $value->{last($attributes)};'); } else { if (count($param->getAttributes()) === 1 && !empty($param->getValue())) { return eval('return $value->{head($param->getAttributes())} ' . $exp . ' $param->getValue();'); } } } return false; }); } } return $collection; }
/** * Display a listing of the resource. * * @return Response */ public function index() { $servers = Server::paginate(); $collection = new Collection(); foreach ($servers as $server) { try { $query = new Swat4Server($server->ip_address, $server->query_port); $query->query(); } catch (\Exception $e) { continue; } $serverquery = json_decode($query); if ($serverquery->hostname == '...server is reloading or offline' || $serverquery->hostname == null || $serverquery->hostname == "" || empty($serverquery->hostname)) { continue; } $newserver = new Arr(); $newserver->hostname = html_entity_decode(fixHostNameForServerList($serverquery->hostname)); $newserver->map = $serverquery->map; $newserver->gametype = $serverquery->gametype; $newserver->version = $serverquery->patch; $newserver->players_current = $serverquery->players_current; $newserver->players_max = $serverquery->players_max; $newserver->ip_address = $server->ip_address; $newserver->join_port = $server->join_port; $newserver->id = $server->id; $newserver->rank = $server->rank; $collection->push($newserver); } //$collection = $collection->sortByDesc('players_current'); $collection = $collection->sortByDesc(function ($server) { return $server->players_current > 0 ? $server->players_current : $server->rank; }); return view('server.list')->with('servers', $collection)->with('page', $servers); }
/** * Apply given filters on media. * * @param \Illuminate\Support\Collection $media * @param array|callable $filter * * @return Collection */ protected function applyFilterToMediaCollection(Collection $media, $filter) : Collection { if (is_array($filter)) { $filter = $this->getDefaultFilterFunction($filter); } return $media->filter($filter); }
/** * CollectionProvider constructor. * @param Collection $collection The collection with the initial data */ public function __construct(Collection $collection) { $this->collection = $collection; $this->totalInitialDataCount = $collection->count(); $this->setupSearch(); $this->setupOrder(); }
/** * @param Collection $films * @return Collection */ public function transformCollection(Collection $films) { $transformedFilms = $films->map(function (Film $film) { return ['id' => $film->id, 'title' => $film->title, 'original_title' => $film->original_title, 'years' => $film->years, 'countries' => $film->countries()->get(), 'synopsis' => $film->synopsis, 'director' => $film->director, 'created_at' => $film->created_at->toDateString(), 'cover' => ['thumbnail' => $film->image->url('thumbnail')]]; }); return $transformedFilms; }
/** * This method generates a full report for the given period on all * given accounts. * * a special consideration for accounts that did exist on this exact day. * we also grab the balance from today just in case, to see if that changes things. * it's a fall back for users who (rightly so) start keeping score at the first of * the month and find the first report lacking / broken. * * @param Carbon $start * @param Carbon $end * @param Collection $accounts * * @return AccountCollection */ public function getAccountReport(Carbon $start, Carbon $end, Collection $accounts) : AccountCollection { $startAmount = '0'; $endAmount = '0'; $diff = '0'; $ids = $accounts->pluck('id')->toArray(); $yesterday = clone $start; $yesterday->subDay(); $startSet = $this->getSet($ids, $yesterday); // get balances for start. $backupSet = $this->getSet($ids, $start); $endSet = $this->getSet($ids, $end); $accounts->each(function (Account $account) use($startSet, $endSet, $backupSet) { return self::reportFilter($account, $startSet, $endSet, $backupSet); }); // summarize: foreach ($accounts as $account) { $startAmount = bcadd($startAmount, $account->startBalance); $endAmount = bcadd($endAmount, $account->endBalance); $diff = bcadd($diff, bcsub($account->endBalance, $account->startBalance)); } $object = new AccountCollection(); $object->setStart($startAmount); $object->setEnd($endAmount); $object->setDifference($diff); $object->setAccounts($accounts); return $object; }
function tour_compare_add() { $id = request()->input('id'); if ($id) { $query['id'] = $id; $query['with_travel_agent'] = true; $api_response = json_decode($this->api->get($this->api_url . '/tours?' . http_build_query(array_merge($query, ['access_token' => Session::get('access_token')])))->getBody()); if ($api_response->data->data[0]) { $tour = $api_response->data->data[0]; $comparison = session()->get('tour_comparison'); if (!$comparison) { $comparison = new Collection(); } // Check if there's already max amount of comparable tour if ($comparison->count() >= 4) { return response()->json(JSend::fail(['comparison' => 'Tidak dapat membandingkan lebih dari 4 paket tour'])->asArray()); } // Make sure no duplicated tour if (!$comparison->where('_id', $tour->_id)->count()) { $comparison->push($tour); } session()->put('tour_comparison', $comparison); return response()->json(JSend::success($comparison->toArray())->asArray()); } else { return app::abort(404); } } else { return app()->abort(400); } }
/** * @return Collection */ public function getCategories() { $set = $this->categories->sortByDesc(function (CategoryModel $category) { return $category->spent; }); return $set; }
/** * Bootstrap the application services. */ public function boot() { parent::boot(); $this->publishMigrations(); $app = $this->app; if ($app->bound('form')) { $app->form->macro('selectCountry', function ($name, $selected = null, $options = []) use($app) { $countries = Cache::rememberForever('brianfaust.countries.select.name.cca2', function () { $records = Country::get(['name', 'cca2']); $countries = new Collection(); $records->map(function ($item) use(&$countries) { $countries[$item['cca2']] = $item['name']['official']; }); return $countries->sort(); }); return $app->form->select($name, $countries, $selected, $options); }); $app->form->macro('selectCountryWithId', function ($name, $selected = null, $options = []) use($app) { $countries = Cache::rememberForever('brianfaust.countries.select.id.cca2', function () { $records = Country::get(['name', 'id']); $countries = new Collection(); $records->map(function ($item) use(&$countries) { $countries[$item['id']] = $item['name']['official']; }); return $countries->sort(); }); return $app->form->select($name, $countries, $selected, $options); }); } }
/** * Register the location. * * @return void */ public function register() { if (empty($this->migrate)) { return false; } $this->locations->push([$this->migrate, $this->using ?: null]); }
/** * Summarizes all income and expenses, per month, for a given year. * * @param ReportQueryInterface $query * @param $year * @param bool $shared * * @return \Symfony\Component\HttpFoundation\Response */ public function yearInOut(ReportQueryInterface $query, $year, $shared = false) { // get start and end of year $start = new Carbon($year . '-01-01'); $end = new Carbon($year . '-12-31'); $shared = $shared == 'shared' ? true : false; // chart properties for cache: $cache = new CacheProperties(); $cache->addProperty('yearInOut'); $cache->addProperty($year); $cache->addProperty($shared); if ($cache->has()) { return Response::json($cache->get()); // @codeCoverageIgnore } $entries = new Collection(); while ($start < $end) { $month = clone $start; $month->endOfMonth(); // total income and total expenses: $incomeSum = $query->incomeInPeriodCorrected($start, $month, $shared)->sum('amount_positive'); $expenseSum = $query->expenseInPeriodCorrected($start, $month, $shared)->sum('amount_positive'); $entries->push([clone $start, $incomeSum, $expenseSum]); $start->addMonth(); } $data = $this->generator->yearInOut($entries); $cache->store($data); return Response::json($data); }
/** * Extension list. * * @return \Illuminate\Support\Collection * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException */ public function getExtensions() { if ($this->extensions->isEmpty()) { if ($this->files->isDirectory($this->getExtensionPath()) && !empty($vendors = $this->files->directories($this->getExtensionPath()))) { collect($vendors)->each(function ($vendor) { if ($this->files->isDirectory($vendor) && !empty($directories = $this->files->directories($vendor))) { collect($directories)->each(function ($directory) { 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-extension' && ($name = Arr::get($package, 'name'))) { $extension = new Extension($name); $extension->setAuthor(Arr::get($package, 'authors')); $extension->setDescription(Arr::get($package, 'description')); if ($entries = data_get($package, 'autoload.psr-4')) { foreach ($entries as $namespace => $entry) { $extension->setEntry($namespace . 'Extension'); } } $this->extensions->put($directory, $extension); } } }); } }); } } return $this->extensions; }
/** * @return Collection */ public function getExtensions() { $extensionsDir = $this->getExtensionsDir(); $dirs = array_diff(scandir($extensionsDir), ['.', '..']); $extensions = new Collection(); $installed = json_decode(file_get_contents(public_path('vendor/composer/installed.json')), true); foreach ($dirs as $dir) { if (file_exists($manifest = $extensionsDir . '/' . $dir . '/composer.json')) { $extension = new Extension($extensionsDir . '/' . $dir, json_decode(file_get_contents($manifest), true)); if (empty($extension->name)) { continue; } foreach ($installed as $package) { if ($package['name'] === $extension->name) { $extension->setInstalled(true); $extension->setVersion($package['version']); $extension->setEnabled($this->isEnabled($dir)); } } $extensions->put($dir, $extension); } } return $extensions->sortBy(function ($extension, $name) { return $extension->composerJsonAttribute('extra.flarum-extension.title'); }); }
/** * @param string $rss * @param int $limit * * @return array */ protected function parseRss($rss, $limit = 0) { // Load the feed $feed = simplexml_load_string($rss, 'SimpleXMLElement', LIBXML_NOCDATA); // Make limit an integer $limit = (int) $limit; // Feed could not be loaded if ($feed === false) { return new Collection(); } $namespaces = $feed->getNamespaces(true); // Detect the feed type. RSS 1.0/2.0 and Atom 1.0 are supported. $feed = isset($feed->channel) ? $feed->xpath('//item') : $feed->entry; $i = 0; $items = new Collection(); foreach ($feed as $item) { if ($limit > 0 and $i++ === $limit) { break; } $item_fields = (array) $item; // get namespaced tags foreach ($namespaces as $ns) { $item_fields += (array) $item->children($ns); } $items->push($item_fields); } return $items; }
function getTotalUpcomingSchedulesAttribute() { if (!isset($this->total_upcoming_schedules)) { $destination_ids = new Collection(); $destination_ids->push($this->id); foreach ($this->descendant as $x) { $destination_ids->push($x->id); } $this->total_upcoming_schedules = TourSchedule::whereHas('tour', function ($query) use($destination_ids) { $query->InDestinationByIds($destination_ids); })->scheduledBetween(\Carbon\Carbon::now(), \Carbon\Carbon::now()->addYear(5))->count(); } return $this->total_upcoming_schedules; // $destination_ids = Static::where(function($query) uses ($this) { // $query->where('id', '=', $this->id) // ->orWhere($this->getPathField(), 'like', $this->attributes[$this->getPathField()] . Static::getDelimiter() . '%') // })->join('tours', 'tours.') // // calculate this destination total schedules // $total_schedule = 0; // foreach ($this->tours as $tour) // { // $total_schedule += $tour->schedules->count(); // } // // calculate this destination and its children total schedules // $descendants = $this->descendant; // $descendants->load('tours', 'tours.schedules'); // foreach ($descendants as $descendant) // { // foreach ($descendant->tours as $tour) // { // $total_schedule += $tour->schedules->count(); // } // } // return $total_schedule; }
public function __set($key, $value) { switch ($key) { case 'odeme_yontem_bilgi_model': $value = new SiparisOdemeYontem($value); break; case 'kargo_yontem_bilgi_model': $value = new SiparisKargoYontem($value); break; case 'fatura_adres_bilgi_model': $value = new SiparisAdres($value); break; case 'teslimat_adres_bilgi_model': $value = new SiparisAdres($value); break; case 'fatura_adres': $value = new SiparisAdres($value); break; case 'teslimat_adres': $value = new SiparisAdres($value); break; case 'durum': $value = new SiparisDurum($value); break; case 'urunler': $collection = new Collection(); foreach ($value as $item) { $collection->push(new SiparisUrun($item)); } $value = $collection; break; } parent::__set($key, $value); }
function index(Request $request) { ///////////////// // Load Filter // ///////////////// $filters = $request->only('name', 'skip', 'take', 'with_count', 'id'); /////////// // Query // /////////// if (!$filters['take']) { $filters['take'] = 50; } else { $filters['take'] = min($filters['take'] * 1, 50); } $filters['skip'] = $filters['skip'] * 1; if ($filters['id']) { $data = new Collection(); $dt = Model::find($filters['id']); $data->push($dt); if ($filters['with_count']) { $count = $q->count(); } } else { $q = Model::name($filters['name']); if ($filters['with_count']) { $count = $q->count(); } $data = $q->select('*')->skip($filters['skip'])->take($filters['take'])->get(); } ////////////// // Response // ////////////// return response()->json(JSend::success(['count' => $count, 'data' => $data->toArray()])->asArray()); }
/** * @param $object * @param Carbon $start * @param Carbon $end * @param Collection $accounts * * @return string */ protected function commonBalanceInPeriod($object, Carbon $start, Carbon $end, Collection $accounts) { $ids = $accounts->pluck('id')->toArray(); $entry = $object->transactionjournals()->transactionTypes([TransactionType::WITHDRAWAL, TransactionType::DEPOSIT, TransactionType::OPENING_BALANCE])->before($end)->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')->leftJoin('accounts', 'accounts.id', '=', 'transactions.account_id')->whereIn('accounts.id', $ids)->after($start)->first([DB::raw('SUM(`transactions`.`amount`) as `journalAmount`')]); $amount = $entry->journalAmount; return $amount; }
public function __set($key, $value) { switch ($key) { case 'kategori': $value = new ProductCategory($value); break; case 'resimler': $collection = new Collection(); foreach ($value as $item) { $collection->push(new Resim($item)); } $value = $collection; break; case 'ozellikler': $collection = new Collection(); foreach ($value as $item) { $collection->push(new Ozellik($item)); } $value = $collection; break; case 'categories': $collection = new Collection(); foreach ($value as $item) { $collection->push(new ProductCategory($item)); } $value = $collection; break; } parent::__set($key, $value); }
/** * Create a tree of all branches * * @param array $selected * @param array $branches * @return Illuminate\Support\Collection */ public function all(array $selected, array $branches = []) { $results = $this->cobra5->getStores(); $datastores = []; foreach ($results as $result) { if (in_array($result->name, $selected)) { $datastores[] = $result; } } foreach ($datastores as $datastore) { $datastore = $this->hydrateRoots($datastore); } foreach ($datastores as $datastore) { $datastore = $this->hydrateParents($datastore); } $categories = new Collection(); foreach ($datastores as $datastore) { foreach ($datastore->categories() as $category) { $categories->put($category->id, $category); } } foreach ($categories as $category) { $category = $this->hydrateChildren($category); } if (in_array('documents', $branches)) { foreach ($categories as $category) { $category = $this->hydrateDocuments($category); } } return $categories; }
public function postCalculateMatch($slug, $id, Request $request) { $tournament = KTournament::enabled()->whereSlug($slug)->first(); $match = KMatch::find($id); if (!$tournament || !$match) { abort(404); } //If has enough permissions or not if (!$request->user()->canManageTournament($tournament)) { return redirect()->home(); } if ($match->has_been_played) { return redirect()->route('tournament.bracket.show', [$tournament->slug])->with('error', "Error! Already calculated, Plz contact admin for support"); } $collection = new Collection(); $i = 1; foreach ($request->game_id as $game_id) { //If game_id is 0 means game is not played if ($game_id == 0) { $game = new Game(); $game->game_index = $i; $game->is_played = false; } else { //Get the game $game = Game::findOrFail($game_id); $game->game_index = $i; $game->is_played = true; } $i++; $collection->push($game); } //dd($collection); return view('tournament.manage.getcalculate2')->with('tournament', $tournament)->with('match', $match)->with('games', $collection); }
/** * Test that our results can be filtered down to a single author. */ public function testItFiltersToASingleAuthor() { $authorResults = new Collection(['Steven King' => new Collection(), 'Stephen King' => new Collection()]); $actual = $this->resultCleaner->clean('Steven King', $authorResults, true); $expected = new Collection(['Steven King' => new Collection()]); $this->assertEquals($expected->toArray(), $actual->toArray()); }
public function __set($key, $value) { switch ($key) { case 'kategori': $value = new HaberKategori($value); break; case 'resim_orjinal': case 'resim_detay': case 'resim_kucuk': $value = new Resim($value); break; case 'kullanici_ekleyen': case 'kullanici_hazirlayan': $value = new Kullanici($value); break; case 'galeriler': $values = new Collection(); foreach ($value as $item) { $values->push(new Galeri($item)); } $value = $values; break; } parent::__set($key, $value); }
public function updateMultiple() { $inputs = Input::all(); $collection = new Collection(); for ($i = 0; $i < sizeOf($inputs); $i++) { // get input item // $input = $inputs[$i]; if (array_key_exists('restricted_domain_id', $input)) { // find existing model // $restrictedDomainId = $input['restricted_domain_id']; $restrictedDomain = RestrictedDomain::where('restricted_domain_id', '=', $restrictedDomainId)->first(); $collection->push($restrictedDomain); } else { // create new model // $restrictedDomain = new RestrictedDomain(); } // update model // $restrictedDomain->domain_name = $input['domain_name']; $restrictedDomain->description = $input['description']; // save model // $restrictedDomain->save(); } return $collection; }
public function __construct($presenter, Collection $collection) { foreach ($collection as $key => $resource) { $collection->put($key, new $presenter($resource)); } $this->items = $collection->toArray(); }
/** * @return Collection */ public function getIncomes() { $set = $this->incomes->sortByDesc(function (stdClass $object) { return $object->amount; }); return $set; }
/** * Paginate the results of this query * * @param int * @param int * @return $this */ public function paginate($perPage, $page) { if ($perPage > 0) { $this->collection = $this->collection->forPage($page, $perPage); } return $this; }
/** * @covers FireflyIII\Generator\Chart\Account\ChartJsAccountChartGenerator::frontpage */ public function testFrontpage() { // be somebody $user = FactoryMuffin::create('FireflyIII\\User'); $this->be($user); // create some accounts: $accounts = new Collection(); for ($i = 0; $i < 5; $i++) { $accounts->push(FactoryMuffin::create('FireflyIII\\Models\\Account')); } $preference = FactoryMuffin::create('FireflyIII\\Models\\Preference'); $preference->data = 'en'; $preference->save(); // data for call: $start = Carbon::createFromDate(2015, 1, 1); $end = Carbon::createFromDate(2015, 1, 15); // mock language preference: Preferences::shouldReceive('get')->withArgs(['language', 'en'])->andReturn($preference); // mock Steam::balance Steam::shouldReceive('balance')->withAnyArgs()->andReturn(0); // call $result = $this->object->frontpage($accounts, $start, $end); $this->assertEquals($accounts->count(), $result['count']); $this->assertCount(15, $result['labels']); $this->assertCount($accounts->count(), $result['datasets']); }