count() public method

Count the number of items in the collection.
public count ( ) : integer
return integer
 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('');
 }
 /**
  * Run the actual import
  *
  * @return Collection
  */
 public function createImportEntries() : Collection
 {
     $config = $this->job->configuration;
     $content = $this->job->uploadFileContents();
     // create CSV reader.
     $reader = Reader::createFromString($content);
     $reader->setDelimiter($config['delimiter']);
     $start = $config['has-headers'] ? 1 : 0;
     $results = $reader->fetch();
     Log::notice('Building importable objects from CSV file.');
     foreach ($results as $index => $row) {
         if ($index >= $start) {
             $line = $index + 1;
             Log::debug('----- import entry build start --');
             Log::debug(sprintf('Now going to import row %d.', $index));
             $importEntry = $this->importSingleRow($index, $row);
             $this->collection->put($line, $importEntry);
             /**
              * 1. Build import entry.
              * 2. Validate import entry.
              * 3. Store journal.
              * 4. Run rules.
              */
             $this->job->addTotalSteps(4);
             $this->job->addStepsDone(1);
         }
     }
     Log::debug(sprintf('Import collection contains %d entries', $this->collection->count()));
     Log::notice(sprintf('Built %d importable object(s) from your CSV file.', $this->collection->count()));
     return $this->collection;
 }
Example #3
0
 public function setRelatedModelFields(Collection $relations)
 {
     $this->setModelRelations($relations);
     if ($this->relations->count() > 0) {
         foreach ($this->relations as $relation) {
             if ($relation instanceof Collection) {
                 $this->addModelFields($relation->get('relation')->getEditFields());
             } else {
                 $this->addModelFields($relation->getEditFields());
             }
         }
     }
 }
Example #4
0
 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());
 }
 /**
  * Clean collection by filling in all the blanks.
  */
 public function clean() : Collection
 {
     Log::notice(sprintf('Started validating %d entry(ies).', $this->entries->count()));
     $newCollection = new Collection();
     /** @var ImportEntry $entry */
     foreach ($this->entries as $index => $entry) {
         Log::debug(sprintf('--- import validator start for row %d ---', $index));
         /*
          * X Adds the date (today) if no date is present.
          * X Determins the types of accounts involved (asset, expense, revenue).
          * X Determins the type of transaction (withdrawal, deposit, transfer).
          * - Determins the currency of the transaction.
          * X Adds a default description if there isn't one present.
          */
         $entry = $this->checkAmount($entry);
         $entry = $this->setDate($entry);
         $entry = $this->setAssetAccount($entry);
         $entry = $this->setOpposingAccount($entry);
         $entry = $this->cleanDescription($entry);
         $entry = $this->setTransactionType($entry);
         $entry = $this->setTransactionCurrency($entry);
         $newCollection->put($index, $entry);
         $this->job->addStepsDone(1);
     }
     Log::notice(sprintf('Finished validating %d entry(ies).', $newCollection->count()));
     return $newCollection;
 }
 private function setNamespace()
 {
     $parts = clone $this->endpoint;
     $parts->pop();
     $namespace = $this->endpoint->count() === 1 ? $this->apiNamespace : $this->apiNamespace . '\\' . $parts->implode("\\");
     return $this->writeInTemplate("namespace", $namespace);
 }
 /**
  * Paginates a collection. For simple pagination, one can override this function
  *
  * a little help from http://laravelsnippets.com/snippets/custom-data-pagination
  *
  * @param Collection $data
  * @param int $perPage
  * @param Request $request
  * @param null $page
  *
  * @return LengthAwarePaginator
  */
 public function paginateCollection(Collection $data, $perPage, Request $request, $page = null)
 {
     $pg = $request->get('page');
     $page = $page ? (int) $page * 1 : (isset($pg) ? (int) $request->get('page') * 1 : 1);
     $offset = $page * $perPage - $perPage;
     return new LengthAwarePaginator($data->splice($offset, $perPage), $data->count(), $perPage, Paginator::resolveCurrentPage(), ['path' => Paginator::resolveCurrentPath()]);
 }
Example #8
0
 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);
     }
 }
Example #9
0
 /**
  * @param string|array $_choice
  * @param string       $_value
  *
  * @return $this
  */
 public function addChoice($_choice, $_value = null)
 {
     if (is_array($_choice)) {
         $text = array_get($_choice, 'label');
         $value = array_get($_choice, 'value');
         $atts = array_except($_choice, ['label']);
     } else {
         $text = $_choice;
         $value = is_null($_value) ? $_choice : $_value;
         $atts = ['value' => $value];
     }
     if (!isset($atts['id'])) {
         $atts['id'] = $this->id . '-' . $this->choices->count();
     }
     $choice = new Input($this->type, $this->name, $value, $atts);
     $choice->inputCheckable = true;
     $choice->setAttribute('type', $this->type);
     if ($this->isSelected($value)) {
         $choice->setAttribute('checked', 'checked');
     }
     $choice->addClass($this->type);
     $choice->setLabel($text);
     $choice->setContainer(null);
     $this->choices->push($choice);
     return $this;
 }
 /**
  * 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();
 }
Example #11
0
 protected function save()
 {
     $count_of_changes = $this->added->count() + $this->altered->count() + $this->deleted->count();
     $scan = new FileScan();
     $scan->changes = $count_of_changes;
     $scan->account_id = $this->account->id;
     $scan->save();
 }
Example #12
0
 /**
  * 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;
 }
 public function getForumThreadsByTagsPaginated(Collection $tags, $perPage = 20)
 {
     $query = $this->model->with(['slug', 'mostRecentChild', 'tags'])->where('type', '=', COMMENT::TYPE_FORUM)->join('comment_tag', 'comments.id', '=', 'comment_tag.comment_id');
     if ($tags->count() > 0) {
         $query->whereIn('comment_tag.tag_id', $tags->lists('id'));
     }
     $query->groupBy('comments.id')->orderBy('updated_at', 'desc');
     return $query->paginate($perPage, ['comments.*']);
 }
Example #14
0
 /**
  * Handle the installation request.
  *
  * @param         $step
  * @param Request $request
  * @return mixed
  *
  * @author Cali
  */
 public function postInstall($step, Request $request)
 {
     $this->validateForm($step, $request);
     if ($step == 1) {
         $credentials = ['host' => $request->input('db_host'), 'database' => $request->input('db_name'), 'username' => $request->input('db_user'), 'password' => $request->input('db_password'), 'prefix' => $request->input('db_prefix')];
         if ($this->checkWritability()->checkDatabaseCredentials($credentials)) {
             File::put(base_path('step-1.lock'), '#');
         }
     } else {
         $credentials = ['email' => $request->input('admin_email'), 'username' => $request->input('admin_username'), 'password' => $request->input('admin_password')];
         $this->migrateAndCreateAdmin($credentials);
         return redirect(route('dashboard'));
     }
     if ($this->errorMessages->count()) {
         return redirect(route('install', compact('step'), false))->with(['status' => $this->buildErrorMessages(), 'succeeded' => 0]);
     }
     return redirect(route('install', compact('step'), false))->with(['status' => $this->getSuccessMessages($step), 'succeeded' => 1]);
 }
Example #15
0
 /**
  * Search for any prefixes attached to this route.
  *
  * @return string
  */
 protected function getPrefixes()
 {
     $router = app(\Illuminate\Routing\Router::class);
     $this->prefixes = collect(explode('/', $router->getCurrentRoute()->getPrefix()));
     // Remove the last prefix if it matches the controller.
     $this->prefixes = $this->removeControllerFromPrefixes($this->prefixes);
     if ($this->prefixes->count() > 0) {
         $this->prefix = $this->prefixes->filter()->implode('.');
     }
 }
 /**
  * Fetch some fresh salts and add them to the environment file if they do not already exist.
  *
  * [--file=<path-to-dotenv>]
  * : Path to the environment file.  Default: '.env'
  *
  * [--force]
  * : Overwrite any existing salts in the environment file.
  *
  * @when before_wp_load
  *
  * @param $_
  * @param $assoc_args
  */
 public function generate($_, $assoc_args)
 {
     $this->init_args(func_get_args());
     $updated = $this->update_salts($this->get_flag('force') ?: $this->salts_are_placeholders());
     if (!$this->env->save()) {
         WP_CLI::error('Failed to update salts.');
     }
     $skipped = $updated->pluck('skipped')->filter();
     $set = $this->salts->count() - $skipped->count();
     if ($set === count($this->salts)) {
         WP_CLI::success('Salts generated.');
     } elseif ($set) {
         WP_CLI::success("{$set} salts set.");
     }
     if (!$skipped->isEmpty()) {
         WP_CLI::line('Some keys were already defined in the environment file.');
         WP_CLI::line("Use 'dotenv salts regenerate' to update them.");
     }
 }
 protected function processResponse($response)
 {
     $data = new Collection(json_decode($response->getBody()));
     if ($data->count() == 1) {
         $data = $data->collapse();
     }
     $this->data = $data;
     $this->code = intval($response->getStatusCode());
     $this->response = $response;
 }
Example #18
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     // ------------------------------------------------------------------------------------------------------------
     // GET HEADLINE
     // ------------------------------------------------------------------------------------------------------------
     $headlines = \App\Headline::with('travel_agent')->activeOn(\Carbon\Carbon::now())->orderBy('priority')->get();
     $headlines = $headlines->sortByDesc(function ($data) {
         return $data->travel_agent->active_packages[0]->priority;
     });
     // ------------------------------------------------------------------------------------------------------------
     // GET HOMEGRID
     // ------------------------------------------------------------------------------------------------------------
     $homegrids = \App\HomegridSetting::orderby('name')->get();
     // get upcoming package schedules
     $homegrid_destination_ids = new Collection();
     foreach ($homegrids as $k => $v) {
         if (str_is('destination', $v->type)) {
             $homegrid_destination_ids->push($v->destination);
         }
     }
     if ($homegrid_destination_ids->count()) {
         $homegrid_destinations = \App\Destination::with('tours', 'tours.schedules')->whereIn('id', $homegrid_destination_ids)->get();
         foreach ($homegrids as $k => $v) {
             $homegrids[$k]->destination_detail = $homegrid_destinations->find($v->destination);
         }
     }
     // ------------------------------------------------------------------------------------------------------------
     // QUERY PAKET PROMO TERBARU
     // ------------------------------------------------------------------------------------------------------------
     $tours = \App\Tour::with('destinations', 'schedules', 'destinations.images', 'places', 'places.images', 'travel_agent', 'travel_agent.images', 'images')->has('schedules')->select('tours.*')->join('travel_agencies', 'travel_agencies.id', '=', 'travel_agent_id')->published()->latest('tours.created_at')->limit(8)->groupBy('travel_agent_id')->get();
     // ------------------------------------------------------------------------------------------------------------
     // GET BLOG TERBARU
     // ------------------------------------------------------------------------------------------------------------
     $articles = Article::with('images')->published()->latest('published_at')->take(6)->get();
     // ------------------------------------------------------------------------------------------------------------
     // GET USER
     // ------------------------------------------------------------------------------------------------------------
     $total_subscriber = \App\Subscriber::active()->count();
     $this->info(' ---------------------------------------------------------------------------------------------- ');
     $this->info(' BLAST NEWSLETTER ');
     $this->info(' ---------------------------------------------------------------------------------------------- ');
     $this->info(' * Sending Newsletter to ' . $total_subscriber . ' subscribers');
     \App\Subscriber::with('user')->active()->orderby('id')->chunk(100, function ($subscribers) {
         foreach ($subscribers as $subscriber) {
             Mail::queue('web.v4.emails.newsletters.weekly', ['headlines' => $headlines, 'homegrids' => $homegrids, 'tours' => $tours, 'articles' => $articles, 'subscriber' => $subscriber], function ($m) use($subscriber) {
                 $m->to($subscriber->email, $subscriber->user ? $subscriber->user->name : $subscriber->email)->subject('CAPCUS.id - Newsletter Edisi ' . \Carbon\Carbon::now()->year . '.' . \Carbon\Carbon::now()->format('W'));
             });
             $this->info(' * Newsletter sent to ' . $subscriber->email . ' *');
         }
     });
     $this->info(' ---------------------------------------------------------------------------------------------- ');
     $this->info(' BLAST NEWSLETTER COMPLETED');
     $this->info(' ---------------------------------------------------------------------------------------------- ');
 }
Example #19
0
 public function getAdminPanel()
 {
     $pageName = 'Dashboard';
     $users = Sentry::findAllUsers();
     $newUsers = new Collection($users);
     $userNumber = $newUsers->count();
     $propertyNumber = Property::all()->count();
     $soldPropertyNumber = Property::where('state', '=', 'sold')->count();
     $newsNumber = News::all()->count();
     return view('admin.adminIndex')->with(compact('pageName', 'userNumber', 'propertyNumber', 'soldPropertyNumber', 'newsNumber'));
 }
 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');
 }
 /**
  * @param $resource
  * @param array $arguments
  * @param string $method
  * @return string
  * @throws Exception
  */
 private function call($resource, $arguments, $method)
 {
     try {
         $request = $this->client->{$method}($this->endpoint . $resource, ['headers' => ['Authorization' => 'apikey ' . $this->apikey, 'Content-type' => 'application/json'], 'body' => json_encode($arguments)]);
         $collection = new Collection($request->json());
         if ($collection->count() == 1) {
             return $collection->collapse();
         }
         return $collection;
     } catch (RequestException $e) {
         throw new Exception($e->getResponse()->getBody());
     }
 }
Example #22
0
 /**
  * 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;
 }
 /**
  * CollectionProvider constructor.
  * @param Collection $collection The collection with the initial data
  */
 public function __construct(Collection $collection)
 {
     $this->collection = $collection;
     $this->totalInitialDataCount = $collection->count();
     // define search functions
     $this->globalSearchFunction = function ($data, $search) {
         foreach ($data as $item) {
             if (str_contains(mb_strtolower($item), mb_strtolower($search))) {
                 return true;
             }
         }
         return false;
     };
 }
Example #24
0
 /**
  * @return bool
  */
 public function prepare()
 {
     if ($this->stages->count() === 0) {
         $this->logger->warning("Job has no stages, cannot continue");
         return false;
     }
     foreach ($this->stages as $n => $stage) {
         $this->stageMapping[$stage->getName()] = $n + 1;
         $stage->setJobHandler($this);
         $stage->setLogger($this->logger);
     }
     $this->logger->debug("Prepared Job with {$this->stages->count()} stages");
     return true;
 }
Example #25
0
 /**
  * This method will scan the given transaction journal and check if it matches the triggers found in the Processor
  * If so, it will also attempt to run the given actions on the journal. It returns a bool indicating if the transaction journal
  * matches all of the triggers (regardless of whether the Processor could act on it).
  *
  * @param TransactionJournal $journal
  *
  * @return bool
  */
 public function handleTransactionJournal(TransactionJournal $journal) : bool
 {
     Log::debug(sprintf('handleTransactionJournal for journal %d', $journal->id));
     $this->journal = $journal;
     // get all triggers:
     $triggered = $this->triggered();
     if ($triggered) {
         if ($this->actions->count() > 0) {
             $this->actions();
         }
         return true;
     }
     return false;
 }
 /**
  * @param Type[]|Collection $types
  * @return array
  */
 public function getDefences($types)
 {
     $this->warmUpTypeLookup();
     $result = [];
     if ($types->count() == 1) {
         $typeId = $types[0]->id;
         // check cache
         if (isset($this->singleElementDefensiveCache[$typeId])) {
             return $this->singleElementDefensiveCache[$typeId];
         }
         $firstElementEfficacy = $this->getDefendingTypeEfficacyData($typeId);
         /** @var stdClass $comparison */
         foreach ($firstElementEfficacy as $comparison) {
             $result[$this->typeLookup[$comparison->damage_type_id]] = $comparison->damage_factor;
         }
         // insert to cache
         $this->singleElementDefensiveCache[$typeId] = $result;
         return $result;
     } elseif ($types->count() == 2) {
         $firstTypeId = $types[0]->id;
         $secondTypeId = $types[1]->id;
         $cacheKey = $this->makeDualElementCacheKey($firstTypeId, $secondTypeId);
         if (isset($this->doubleElementDefensiveCache[$cacheKey])) {
             return $this->doubleElementDefensiveCache[$cacheKey];
         }
         $firstElementEfficacy = $this->getDefendingTypeEfficacyData($firstTypeId);
         $secondElementEfficacy = $this->getDefendingTypeEfficacyList($secondTypeId);
         /** @var stdClass $comparison */
         foreach ($firstElementEfficacy as $comparison) {
             $result[$this->typeLookup[$comparison->damage_type_id]] = $comparison->damage_factor * $secondElementEfficacy[$comparison->damage_type_id] / 100;
         }
         // insert to cache
         $this->doubleElementDefensiveCache[$cacheKey] = $result;
         return $result;
     }
     return [];
 }
Example #27
0
 /**
  *
  */
 private function appendLooseAttributes()
 {
     foreach ($this->tabs as $tab) {
         if ($tab->getName() === 'Algemeen') {
             $tab->setAttributes($tab->merge($this->attributes));
             $this->attributes = new Collection();
         }
     }
     if ($this->attributes->count()) {
         $tab = new Tab('Algemeen');
         $tab->setAttributes($this->attributes);
         $this->tabs->prepend($tab);
         $this->attributes = new Collection();
     }
 }
 /**
  * @param TransactionJournal $journal
  *
  * @return bool
  */
 private function applyRules(TransactionJournal $journal) : bool
 {
     if ($this->rules->count() > 0) {
         /** @var Rule $rule */
         foreach ($this->rules as $rule) {
             Log::debug(sprintf('Going to apply rule #%d to journal %d.', $rule->id, $journal->id));
             $processor = Processor::make($rule);
             $processor->handleTransactionJournal($journal);
             if ($rule->stop_processing) {
                 return true;
             }
         }
     }
     return true;
 }
Example #29
0
 /**
  * Create a new field object.
  * @param $name string
  * @param $arguments array
  * @return FieldBlueprint
  */
 protected function createField($name, $arguments)
 {
     $label = array_get($arguments, 0);
     $fieldType = array_get($arguments, 1);
     $fieldArgs = null;
     $inputType = array_get($arguments, 2);
     $inputOpts = array_get($arguments, 3);
     if (is_array($fieldType)) {
         list($fieldType, $fieldArgs) = $fieldType;
     }
     $field = FieldBlueprint::create($name, $fieldType, $fieldArgs, $this)->withInput($label, $inputType, $this->fields->count(), $inputOpts);
     if ($fieldType === FieldBlueprint::TITLE) {
         $this->title = $field;
     }
     return $this->fields[$name] = $field;
 }
Example #30
0
 /**
  * Render the output results to the console
  * 
  * Options
  *  - prefix : The string to prepend to all output
  *  - show_categories : true and we will render the categories for an item
  *  
  * @param Collection $items
  * @param array $options 
  */
 protected function render(Collection $items, $options = array())
 {
     $defaults = array('prefix' => '', 'show_categories' => true);
     $options += $defaults;
     if ($items->count() == 0) {
         $this->info("No results found.");
         return;
     }
     foreach ($items as $item) {
         $this->info("{$options['prefix']}{$item->getId()} {$item->getName()} ({$item->getQuantity()})");
         if ($options['show_categories']) {
             foreach ($item->getCategories() as $cat) {
                 $this->info("{$options['prefix']}- {$cat}");
             }
         }
         $this->info("");
     }
 }