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(''); }
/** * На самом деле тут у меня фантация играет по полной, поймать мошеника это круто * можно было реализовать из hidden risk некую битовую маску и по ней уже обсчитывать мошеников * @param Collection $leaders * @param []Collection $prevLeaders * @return []Collection */ public function __invoke(Collection $leaders, array $prevLeaders) { $leaders->each(function ($value) use($prevLeaders) { $id = object_get($value, 'id', null); $score = object_get($value, 'score', null); // Идем по списку лидеров foreach ($prevLeaders as $leaders) { $leaders->each(function ($leader) use($id, $score) { // Если личдер найден if ($leader->id === $id) { // И он есть в hidden risk if (isset($this->hidRisk[$id])) { // Удаляем его unset($this->hidRisk[$id]); } // Если сейчас у него очков больше чем в прошлый раз if ($leader->score < $score / static::RISK_GROWTH_SCOPE) { $this->result[$id] = $leader; } else { $this->hidRisk[$id] = $leader; } } }); } if (isset($this->hidRisk[$id])) { $this->result[$id] = $value; } }); return $this->result; }
/** * Start the site Scraping process. * * @return void */ public function scrape() { $scrape = new Scrape(new Client()); $this->list->each(function ($url) use($scrape) { $this->writePage($url, $scrape->run($url)); }); }
/** * Set up test environment. */ public function setUp() { parent::setUp(); $this->company = factory(Company::class)->create(); $this->users = factory(User::class, 5)->create(['company_id' => $this->company->id]); $this->users->each(function ($user) { factory(Task::class, 5)->create(['user_id' => $user->id]); }); }
public function tearDown() { $this->filesCreated->each(function ($file) { try { unlink($file); } catch (Exception $e) { } }); parent::tearDown(); }
/** * @return void */ public function placeWidgetsToLayoutBlocks() { $this->sortWidgets(); $this->registeredWidgets->each(function (WidgetCollectionItem $widget) { if (method_exists($widget->getObject(), 'onLoad')) { app()->call([$widget->getObject(), 'onLoad']); } })->each(function (WidgetCollectionItem $widget) { if (method_exists($widget->getObject(), 'afterLoad')) { app()->call([$widget->getObject(), 'afterLoad']); } }); }
/** * @param \Illuminate\Support\Collection $files * @return string */ public function compileLess($files) { $files->each(function ($value) { $this->less->parseFile($value); }); return $this->less->getCss(); }
protected function cleanUp(Collection $cleanableModels) { $cleanableModels->each(function (string $modelClass) { $numberOfDeletedRecords = $modelClass::cleanUp($modelClass::query())->delete(); event(new ModelWasCleanedUp($modelClass, $numberOfDeletedRecords)); $this->info("Deleted {$numberOfDeletedRecords} record(s) from {$modelClass}."); }); }
/** * Execute the job. * * @return Collection */ public function handle() { for ($i = 1; $i <= $this->amount; $i++) { $this->codes->push($this->generateCode()); } $this->checkDatabase(); /** @var \Illuminate\Database\Eloquent\Collection $products */ $products = collect(); /** * Now it is safe to add to the DB */ $this->codes->each(function ($code) use($products) { $products->push(new Code(compact('code'))); }); $this->product->codes()->saveMany($products); return $products; }
/** * Get the array representation of attributes * @return array Assoc array with attribute name in the key * @since 1.0 */ public function toArray() { $returnArr = []; $this->attributes->each(function ($attribute) use(&$returnArr) { /* @var ConfigurationAttribute $attribute **/ $returnArr[$attribute->getName()] = $attribute->getValue(); }); return $returnArr; }
public function run() { $this->backupDestinations->each(function (BackupDestination $backupDestination) { try { if (!$backupDestination->isReachable()) { throw new Exception("Could not connect to disk {$backupDestination->diskName()} because: {$backupDestination->connectionError()}"); } consoleOutput()->info("Cleaning backups of {$backupDestination->backupName()} on disk {$backupDestination->diskName()}..."); $this->strategy->deleteOldBackups($backupDestination->backups()); event(new CleanupWasSuccessful($backupDestination)); $usedStorage = Format::humanReadableSize($backupDestination->usedStorage()); consoleOutput()->info("Used storage after cleanup: {$usedStorage}."); } catch (Exception $exception) { consoleOutput()->error("Cleanup failed because: {$exception->getMessage()}."); event(new CleanupHasFailed($exception)); } }); }
/** * @param Collection $leaders * @param []Collection $prevLeaders Массив ранее собраных списков * @return array */ public function __invoke(Collection $leaders, array $prevLeaders) { $leaders->each(function ($value) use($prevLeaders) { $id = object_get($value, 'id', null); $place = object_get($value, 'place', null); $this->result[$id] = 0; foreach ($prevLeaders as $leaders) { $leaders->each(function ($value) use($id, $place) { if ($value->id === $id) { if ($value->place !== $place) { $this->result[$id]++; } } }); } }); return $this->result; }
public function saveChannels(Collection $data) { $data->each(function ($item, $key) { $item->persist(); $game = $this->game->get($item->relatedGame); if (!is_null($game)) { $item->relatesToGame($game); } }); }
/** * Send the notification to devices. * Returns errors (APNs and GCM) and updated token (GCM). * * @return array [ 'errors': [ Device, ... ], 'updates' => [ [ 'device' => Device, 'token' => 'a-new-token' ], ... ] ] */ public function send() { $apns = new Collection(); $gcm = new Collection(); $this->devices->each(function (Device $device) use(&$apns, &$gcm) { if ($device->isApns()) { $apns->push($this->merge($device)); } elseif ($device->isGcm()) { $gcm->push($this->merge($device)); } }); $results = ['errors' => [], 'updates' => []]; $this->mergeResults($results, $this->pushApns($apns)); $this->mergeResults($results, $this->pushGcm($gcm)); // Reset $apns = null; $gcm = null; $this->device = new Collection(); return $results; }
protected function removeBackupsForAllPeriodsExceptOne(Collection $backupsPerPeriod) { $backupsPerPeriod->each(function (Collection $groupedBackupsByDateProperty, string $periodName) { $groupedBackupsByDateProperty->each(function (Collection $group) { $group->shift(); $group->each(function (Backup $backup) { $backup->delete(); }); }); }); }
protected function createDistributedPathDirs() { $dirPath = ''; $this->distributedPathCollection->each(function ($prefix) use(&$dirPath) { $dirPath .= $this->pathSeparator . $prefix; $fullPath = parent::getPathPrefix() . $dirPath; if (!is_dir($fullPath)) { @mkdir(parent::getPathPrefix() . $dirPath); } }); return $this; }
protected function copyToBackupDestinations(string $path) { $this->backupDestinations->each(function (BackupDestination $backupDestination) use($path) { try { consoleOutput()->info("Copying zip to disk named {$backupDestination->diskName()}..."); $backupDestination->write($path); consoleOutput()->info("Successfully copied zip to disk named {$backupDestination->diskName()}."); event(new BackupWasSuccessful($backupDestination)); } catch (Exception $exception) { consoleOutput()->error("Copying zip failed because: {$exception->getMessage()}."); event(new BackupHasFailed($exception, $backupDestination ?? null)); } }); }
/** * @return \Illuminate\Database\Eloquent\Collection|FieldGroupInterface */ public function getGroupedFields() { $groups = FieldGroup::all()->map(function ($field) { return $field->setFields([]); })->keyBy('id'); $defaultGroup = (new DefaultGroup())->setFields([]); $this->fields->each(function (FieldInterface $field) use($groups, $defaultGroup) { if ($groups->offsetExists($field->group_id) and !is_null($group = $groups->offsetGet($field->group_id))) { $group->addField($field); } else { $defaultGroup->addField($field); } }); return $groups->add($defaultGroup); }
/** * This method generates a full report for the given period on all * given accounts * * @param Carbon $start * @param Carbon $end * @param Collection $accounts * * @return AccountCollection */ public function getAccountReport(Carbon $start, Carbon $end, Collection $accounts) { $startAmount = '0'; $endAmount = '0'; $diff = '0'; $ids = $accounts->pluck('id')->toArray(); $yesterday = clone $start; $yesterday->subDay(); bcscale(2); // get balances for start. $startSet = Account::leftJoin('transactions', 'transactions.account_id', '=', 'accounts.id')->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')->whereIn('accounts.id', $ids)->whereNull('transaction_journals.deleted_at')->whereNull('transactions.deleted_at')->where('transaction_journals.date', '<=', $yesterday->format('Y-m-d'))->groupBy('accounts.id')->get(['accounts.id', DB::Raw('SUM(`transactions`.`amount`) as `balance`')]); // and end: $endSet = Account::leftJoin('transactions', 'transactions.account_id', '=', 'accounts.id')->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')->whereIn('accounts.id', $ids)->whereNull('transaction_journals.deleted_at')->whereNull('transactions.deleted_at')->where('transaction_journals.date', '<=', $end->format('Y-m-d'))->groupBy('accounts.id')->get(['accounts.id', DB::Raw('SUM(`transactions`.`amount`) as `balance`')]); $accounts->each(function (Account $account) use($startSet, $endSet) { /** * The balance for today always incorporates transactions * made on today. So to get todays "start" balance, we sub one * day. */ // $currentStart = $startSet->filter(function (Account $entry) use($account) { return $account->id == $entry->id; }); if ($currentStart->first()) { $account->startBalance = $currentStart->first()->balance; } $currentEnd = $endSet->filter(function (Account $entry) use($account) { return $account->id == $entry->id; }); if ($currentEnd->first()) { $account->endBalance = $currentEnd->first()->balance; } }); // 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; }
/** * Verifies whether given modules exist and whether they are active * * @param Collection $moduleNames * @param bool $verifyActive * * @return Collection|bool */ private function verifyModules(Collection $moduleNames, $verifyActive) { $modules = collect(); $moduleNames->each(function ($name) use($verifyActive, $modules) { /** @var Module $module */ $module = $this->laravel['modular']->find($name); if (!$module) { $this->error("Module {$name} does not exist"); return; } if ($verifyActive && !$module->active()) { $this->error("Module {$name} is not active"); return; } $modules->push($module); }); return $modules; }
/** * {@inheritdoc} */ public function applySorts($query) { $this->query = $query; $this->sorts->each(function ($sort) { /** @var Sort $sort */ $field = $sort->getField(); $method = $this->getSortMethod($field); if (method_exists($this, $method)) { $this->{$method}($sort->getOrder()); $this->appliedSorts->push($field); } elseif (in_array($field, $this->simpleSorts)) { $this->applySimpleSort($sort); $this->appliedSorts->push($field); } }); $this->applyDefaultSorts(); return $this->query; }
/** * Get all the assets. * * @return \Illuminate\Support\Collection */ public function getAssets() { $assets = $this->assets; // Spin through each directory and recursively merge the current directories assets // on to the directories assets. This maintains the order of adding in the array // structure. $this->directories->each(function ($directory) use(&$assets) { $assets = $directory->getAssets()->merge($assets); }); // Spin through each of the filters and apply them to each of the assets. Every filter // is applied and then later during the build will be removed if it does not apply // to a given asset. $this->filters->each(function ($filter) use(&$assets) { $assets->each(function ($asset) use($filter) { $asset->apply($filter); }); }); return $assets; }
/** * Seed data ... * * @param Collection $data * @param $env * @return array */ public function seed(Collection $data, $env) { DB::transaction(function () use($env, $data) { $data->each(function ($seed) use($env) { $class = getFirstKeyArray($seed); $batch = self::getRepository()->getNextBatch($env); $message = ''; $classSeeded = str_singular($class) . '_' . $env; if (self::isSeed($classSeeded, $env)) { self::updateSeed(self::getSeed($classSeeded, $env)->id, $seed['hash']); $message = sprintf("%s was updated successfully", ucfirst(str_singular($class))); self::rollbackProcessing(array_reverse(array_unique(getModelsSeed($seed)))); } else { self::getRepository()->addSeed($classSeeded, $seed['hash'], $env, $batch); $message = sprintf("%s was updated successfully", ucfirst(str_singular($class))); } self::seedProcessing(str_singular($class), null, $seed[$class]); self::getCommand()->info($message); }); }); }
/** * Save and resize the image * @param ImageManager $resizer * @return void */ public function handle(ImageManager $resizer, Filesystem $filesystem) { $filesystem->makeDirectory($this->path, 0755, true, true); $image = $resizer->make($this->source); $image->backup(); $this->sizes->each(function ($dims, $size) use($resizer, $image) { $size = !$size || $size === 'default' ? '' : "{$size}_"; $dest = "{$this->path}/{$size}{$this->filename}"; if ($dims->width && !$dims->height) { $image->resize($dims->width, null, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); })->save($dest, $this->quality); } else { if ($dims->height && !$dims->width) { $image->resize(null, $dims->height, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); })->save($dest, $this->quality); } else { if ($dims->padding) { $image->resize($dims->width - $dims->padding, $dims->height - $dims->padding, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }); } else { $image->fit($dims->width, $dims->height, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }); } $resizer->canvas($dims->width, $dims->height, $dims->bg)->insert($image, 'center')->save($dest, $this->quality); } } $image->reset(); }); $image->destroy(); }
/** * 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; }
public function testEach() { $c = new Collection($original = [1, 2, 'foo' => 'bar', 'bam' => 'baz']); $result = []; $c->each(function ($item, $key) use(&$result) { $result[$key] = $item; }); $this->assertEquals($original, $result); $result = []; $c->each(function ($item, $key) use(&$result) { $result[$key] = $item; if (is_string($key)) { return false; } }); $this->assertEquals([1, 2, 'foo' => 'bar'], $result); }
/** * Append the parameters subsection to a resource or action. * * @param string $contents * @param \Illuminate\Support\Collection $parameters * * @return void */ protected function appendParameters(&$contents, Collection $parameters) { $this->appendSection($contents, 'Parameters'); $parameters->each(function ($parameter) use(&$contents) { $contents .= $this->line(); $contents .= $this->tab(); $contents .= sprintf('+ %s (%s, %s) - %s', $parameter->identifier, $parameter->members ? sprintf('enum[%s]', $parameter->type) : $parameter->type, $parameter->required ? 'required' : 'optional', $parameter->description); if (isset($parameter->default)) { $this->appendSection($contents, sprintf('Default: %s', $parameter->default), 2, 1); } if (isset($parameter->members)) { $this->appendSection($contents, 'Members', 2, 1); foreach ($parameter->members as $member) { $this->appendSection($contents, sprintf('`%s` - %s', $member->identifier, $member->description), 3, 1); } } }); }
*/ $app = new \Slim\Slim(); $app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware()); $app->get('/', function () { echo '<pre>'; // MessageBag init $messageBag = new MessageBag(); // Array dot notation (and other helpers) $person = ['name' => ['first' => 'Jill', 'last' => 'Schmoe']]; echo 'name.first is ' . array_get($person, 'name.first') . "\n"; $messageBag->add('notice', 'Array dot notation displayed.'); echo '<hr>'; // Collection $people = new Collection(['Declan', 'Abner', 'Mitzi']); $people->each(function ($person) { echo "Collection person: {$person}\n"; }); $messageBag->add('notice', 'Collection displayed.'); echo '<hr>'; // More at http://daylerees.com/codebright/eloquent-collections // Fluent $personRecord = array('first_name' => 'Mohammad', 'last_name' => 'Gufran'); $record = new Fluent($personRecord); $record->address('hometown, street, house'); echo $record->first_name . "\n"; echo $record->address . "\n"; $messageBag->add('notice', 'Fluent displayed.'); echo '<hr>'; // Pluralizer $item = 'goose'; echo "One {$item}, two " . Pluralizer::plural($item) . "\n";
/** * @param $scrapers Collection **/ protected function scheduleScrapers(Collection $scrapers) { $scrapers->each(function ($scraperName) { $this->scheduleScraperRun($scraperName); }); }
/** * 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; }