sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function sanitize($preferences = null) : Collection { if (is_null($preferences) && $this->auth->check()) { return Collection::make($this->auth->user()->preferences); } if (is_null($preferences) && ! $this->auth->check()) { return $this->allowed; } if (is_string($preferences)) { $preferences = json_decode($preferences, true); } return Collection::make($preferences)->filter(function($item, $key) { return $this->allowed->has($key); }); }
Sanitizes the given preferences. @param null|string $preferences @return Collection
entailment
public function update(string $key, $data) { if (is_string($data)) { $data = $this->normalizeToCollection($data); } if ($this->allowed->has($key)) { $this->updatePreferencesForKey( $key, $this->normalizedTags($data) ); $this->updateCategories( $data->pluck('category_id')->unique() ); } return $this; }
Updates the user preferences for a given key and data. @param string $key @param mixed $data @return self
entailment
protected function normalizedTags($data) : Collection { return $data->has('tags') ? Collection::make($data->get('tags')) : $data->pluck('tags'); }
Returns a collection of tags. @param mixed $data @return Collection
entailment
protected function updatePreferencesForKey(string $key, Collection $tags) { $tags = str_replace('"', '', $tags->implode(',')); $tags = Collection::make(explode(',', $tags)) ->merge(explode(',',$this->preferences[$key])) ->unique() ->take(self::MAX_TAGS) ->implode(','); $this->preferences[$key] = rtrim($tags, ','); }
Updates the user references for a given key. @param string $key @param Collection $tags @return void
entailment
protected function updateCategories(Collection $data) { $ids = explode(',', $this->preferences['product_categories']); $categories = Collection::make($ids) ->merge($data) ->unique() ->take(self::MAX_TAGS) ->implode(','); $this->preferences['product_categories'] = trim($categories, ','); }
Updates the user categories key with the given collection. @param Collection $data @return void
entailment
public function pluck($key) : Collection { if (! $this->preferences->has($key)) { return new Collection; } return Collection::make( explode(',', $this->preferences[$key]) ); }
Plucks the given key from the user preferences. @param string $key @return Collection
entailment
public function all($keys = []) : Collection { if (count($keys) == 0) { $keys = $this->preferences->keys(); } if (is_string($keys)) { $keys = [$keys]; } return Collection::make($keys)->flatMap(function ($item) { if (isset($this->preferences[$item])) { $result[$item] = explode(',', $this->preferences[$item]); } return $result ?? []; }); }
Takes the given keys from the preferences array. @param string|array $keys @return Collection
entailment
public function query() : Builder { if (trim($seed = $this->seed) !== '') { $this->builder->where(function ($query) use ($seed) { return $this->resolveQuery($query, $seed); }); } return $this->builder; }
Builds the query with the given category. @return Builder
entailment
protected function resolveQuery(Builder $builder, string $seed) : Builder { foreach ($this->searchable as $field) { $builder->orWhere($field, 'like', '%'.urldecode($seed).'%'); } return $builder; }
Resolves the query for the given seed. @param Builder $builder @param string $seed @return Builder
entailment
public function filterable($limit = 5) { $key = md5(vsprintf('%s', ['filterable_features'])); return Cache::remember($key, $this->remembering, function () use ($limit) { return $this->next->filterable($limit); }); }
Exposes the features allowed to be in the products filtering. @param integer $limit @return \Illuminate\Database\Eloquent\Collection
entailment
public function filterableValidationRules() : array { $key = md5(vsprintf('%s', ['features_validationRules'])); return Cache::remember($key, $this->remembering, function () { return $this->next->filterableValidationRules(); }); }
Returns an array with the validation rules for the filterable features. @return array
entailment
protected function registerPolicies() { foreach ($this->policies as $model => $policy) { Gate::policy($model, $policy); } }
Register the antvel policies. @return void
entailment
public function setValidationRulesAttribute($value) { //If the passed value is a string, we assume the request wants to save a validation //string. Otherwise, we parse the array given to build such a string. if (is_string($value)) { $this->attributes['validation_rules'] = $value; } else { $this->attributes['validation_rules'] = ValidationRulesParser::parse($value)->toString(); } }
Set the validation_rules with the given value. @param array|string $value @return void
entailment
public function scopeSuggestionsFor($query, string $type, array $tags) { return (new SuggestionQuery($query))->type($type)->apply($tags); }
Returns suggestions for a given tags and type. @param Illuminate\Database\Eloquent\Builder $query @param string $type @param array $tags @return Illuminate\Database\Eloquent\Builder
entailment
public function setPicturesAttribute(array $attr) { $current = $this->image; $image = Images::parse($attr)->on($this->storageFolder()); if ($image->wantsDeletion()) { $image->delete($current); return $this->attributes['image'] = null; } $picture = $image->update($current); return $this->attributes['image'] = $picture['path']; }
Set the image value of a given model. @param array $attr @return null|String
entailment
public function index() { return view('address.list', [ 'addresses' => $addresses = Auth::user()->addresses, 'defaultId' => $addresses->where('default', true)->pluck('id')->first(), ]); }
Signed user's address book. @return void
entailment
public function store(AddressBookRequest $request) { if (Auth::user()->newAddress($request->all())) { return $this->respondsWithSuccess(trans('address.success_save'), route('addressBook.index')); } return $this->respondsWithError(trans('address.errors.update')); }
Store a new address for the signed user. @return void
entailment
public function edit(int $id) { try { $address = Auth::user()->findAddress($id); } catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return $this->respondsWithError(trans('address.errors.model_not_found')); } return view('address.form_edit', compact('address')); }
Show the edition address form. @param int $id @return void
entailment
public function update(AddressBookRequest $request, int $id) { try { $address = Auth::user()->findAddress($id); } catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return $this->respondsWithError(trans('address.errors.model_not_found')); } $address->update($request->all()); return $this->respondsWithSuccess(trans('address.success_update'), route('addressBook.index')); }
Update a given address. @param AddressBookFormRequest $request @param int $id @return void
entailment
public function destroy(int $id) { try { $address = Auth::user()->findAddress($id); } catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return $this->respondsWithError(trans('address.errors.model_not_found')); } $address->delete(); return $this->respondsWithSuccess('', route('addressBook.index')); }
Remove a given address. @param Request $request @return Void
entailment
public function setDefault(Request $request) { try { $address = Auth::user()->findAddress($request->id); } catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return $this->respondsWithError(trans('address.errors.model_not_found')); } Auth::user()->resetDefaultAddress(); $address->update(['default' => true]); return $this->respondsWithSuccess('', route('addressBook.index')); }
Setting to default a given address. @param Request $request
entailment
protected function categoriesMenu() : array { if (! $this->app->bound($repository = 'category.repository.cahe')) { return []; } return $this->app->make($repository)->categoriesWithProducts()->mapWithKeys(function ($item) { return [$item->id => $item]; })->all(); }
Returns the categories menu. @return array
entailment
public function safeUp() { $this->driver = Craft::$app->getConfig()->getDb()->driver; if ($this->createTables()) { $this->addForeignKeys(); // Refresh the db schema caches Craft::$app->db->schema->refresh(); } return true; }
This method contains the logic to be executed when applying this migration. This method differs from [[up()]] in that the DB logic implemented here will be enclosed within a DB transaction. Child classes may implement this method instead of [[up()]] if the DB logic needs to be within a transaction. @return boolean return a false value to indicate the migration fails and should not proceed further. All other return values mean the migration succeeds.
entailment
protected function parseInput(string $input) { $category = explode('|', $input); if (isset($category[0]) && trim($category[0]) != '') { $this->category_id = urldecode($category[0]); } if (isset($category[1]) && trim($category[1]) != '') { $this->category_name = urldecode($category[1]); } }
Parses the given category info. @param string $input @return void
entailment
public function query() : Builder { if (is_null($this->category_id)) { return $this->builder; } if (count($children = $this->children()) > 0) { $this->builder->whereIn('category_id', $children); } return $this->builder; }
Builds the query with the given category. @return Builder
entailment
protected function children() : array { $categories = App::make('category.repository.cahe')->childrenOf($this->category_id, 50, [ 'id', 'category_id', 'name' ]); return Normalizer::generation($categories) ->prepend((int) $this->category_id) ->all(); }
Returns the children for a given category. @return array
entailment
public static function toJson($features) { if (is_null($features) || count($features) == 0) { return null; } return Collection::make($features)->filter(function ($item) { return trim($item) != ''; })->toJson(); }
Parses the given features to Json. @param array|Collection $features @return null|string
entailment
public static function replaceTheGivenKeyFor($products, $oldKey, $newKey) : array { return $products->mapWithKeys(function ($item) use ($oldKey, $newKey) { $features = $item->features; $features[$newKey] = $features[$oldKey]; unset($features[$oldKey]); return [$item->id => $features]; })->all(); }
Replaces the given key for another in the provided products features collection. @param Collection $products @param string $oldKey @param string $newKey @return Collection
entailment
public static function placeOrders($type_order) { $cart = self::ofType($type_order) ->where('user_id', Auth::user()->id) ->orderBy('id', 'desc') ->first(); $show_order_route = 'orders.show_cart'; $cartDetail = OrderDetail::where('order_id', $cart->id)->get(); $address_id = 0; //When address is invalid, it is because it comes from the creation of a free product. You must have a user direction (Default) if (is_null($cart->address_id)) { $useraddress = Address::auth()->orderBy('default', 'DESC')->first(); if ($useraddress) { $address_id = $useraddress->address_id; } else { return trans('address.no_registered'); } } else { $address_id = $cart->address_id; } $address = Address::where('id', $address_id)->first(); //Checks if the user has points for the cart price and the store has stock //and set the order prices to the current ones if different //Creates the lists or sellers to send mail to $total_points = 0; $seller_email = []; foreach ($cartDetail as $orderDetail) { $product = Product::find($orderDetail->product_id); $seller = User::find($product->updated_by); // dd($product, $seller); if (!in_array($seller->email, $seller_email)) { $seller_email[] = $seller->email; } $total_points += $orderDetail->quantity * $product->price; if ($orderDetail->price != $product->price) { $orderDetail->price = $product->price; $orderDetail->save(); } if ($product->stock < $orderDetail->quantity) { return trans('store.insufficientStock'); } } //Checks if the user has points for the cart price $user = Auth::user(); if ($user->current_points < $total_points && config('app.payment_method') == 'Points') { return trans('store.cart_view.insufficient_funds'); } if (config('app.payment_method') == 'Points') { $negativeTotal = -1 * $total_points; //7 is the action type id for order checkout // $pointsModified = $user->modifyPoints($negativeTotal, 7, $cart->id); // while refactoring } else { $pointsModified = true; } if ($pointsModified) { //Separate the order for each seller //Looks for all the different sellers in the cart $sellers = []; foreach ($cartDetail as $orderDetail) { if (!in_array($orderDetail->product->updated_by, $sellers)) { $sellers[] = $orderDetail->product->updated_by; } } foreach ($sellers as $seller) { //Creates a new order and address for each seller $newOrder = new self(); $newOrder->user_id = $user->id; $newOrder->address_id = $address->id; $newOrder->status = ($type_order == 'freeproduct') ? 'paid' : 'open'; $newOrder->type = ($type_order == 'freeproduct') ? 'freeproduct' : 'order'; $newOrder->seller_id = $seller; $newOrder->save(); $newOrder->seller->notify(new OrderWasUpdated($newOrder)); //moves the details to the new orders foreach ($cartDetail as $orderDetail) { if ($orderDetail->product->updated_by == $seller) { $orderDetail->order_id = $newOrder->id; $orderDetail->save(); } //Increasing product counters. (new ProductsRepository)->increment('sale_counts', $orderDetail->product); //saving tags in users preferences if (trim($orderDetail->product->tags) != '' && auth()->check()) { auth()->user()->updatePreferences('product_purchased', $product->tags); } } } //Changes the stock of each product in the order foreach ($cartDetail as $orderDetail) { $product = Product::find($orderDetail->product_id); $product->stock = $product->stock - $orderDetail->quantity; $product->save(); } foreach ($seller_email as $email) { $mailed_order = self::where('id', $newOrder->id)->with('details')->get()->first(); //Send a mail to the user: Order has been placed $data = [ 'orderId' => $newOrder->id, 'order' => $mailed_order, ]; //dd($data['order']->details,$newOrder->id); $title = trans('email.new_order_for_user.subject')." (#$newOrder->id)"; Mail::send('emails.neworder', compact('data', 'title'), function ($message) use ($user) { $message->to($user->email)->subject(trans('email.new_order_for_user.subject')); }); //Send a mail to the seller: Order has been placed $title = trans('email.new_order_for_seller.subject')." (#$newOrder->id)"; Mail::send('emails.sellerorder', compact('data', 'title'), function ($message) use ($email) { $message->to($email)->subject(trans('email.new_order_for_seller.subject')); }); } return; } else { return trans('store.insufficientFunds'); } }
Start the checkout process for any type of order. @param int $type_order Type of order to be processed @return Response
entailment
public function categoriesWithProducts(array $request = [], $limit = 10, $columns = '*') { $categories = Category::whereHas('products', function($query) { return $query->actives(); }); return $categories->select($columns)->filter($request) ->orderBy('name') ->take($limit) ->get(); }
Returns the categories with products filtered by the given request. @param array $request @param integer $limit @param mixed $columns @return \Illuminate\Database\Eloquent\Collection
entailment
public function childrenOf($category_id, int $limit = 50, $columns = '*') { return Category::select($columns)->with('childrenRecursive') ->where('category_id', $category_id) ->orderBy('updated_at', 'desc') ->take($limit) ->get(); }
Returns the children for the given category. @param Category|mixed $idOrModel $idOrModel @param int $limit @param array $columns @return \Illuminate/Database/Eloquent/Collection
entailment
public function scopeFilter($query, $request) { $request = Arr::only($request, ['name', 'description']); $query->actives()->where(function ($query) use ($request) { foreach ($request as $key => $value) { $query->orWhere($key, 'like', '%' . $value . '%'); } return $query; }); return $query; }
Filter categories by the given request. @param Illuminate\Database\Eloquent\Builder $query @param array $request @return Illuminate\Database\Eloquent\Builder
entailment
public function index(Request $request) { //filter products by the given query. $response['products']['results'] = $this->products->filter([ 'search' => $request->get('q') ], 4)->get(); //filter categories by the given query. $response['products']['categories'] = app('category.repository.cahe')->categoriesWithProducts([ 'name' => $request->get('q'), 'description' => $request->get('q'), ], 4, ['id', 'name']); $response['products']['suggestions'] = Suggestions\Suggest::for('my_searches')->shake()->get('my_searches'); $response['products']['categories_title'] = trans('globals.suggested_categories'); $response['products']['suggestions_title'] = trans('globals.suggested_products'); $response['products']['results_title'] = trans('globals.searchResults'); return $response; }
Loads the products search. @return void
entailment
public static function generation(Collection $categories) : Collection { $ids = []; foreach ($categories as $category) { $ids[] = $category->id; $ids[] = static::familyTree($category->childrenRecursive); } return Collection::make($ids)->flatten()->unique()->sort(); }
Returns the generation ids for the given categories. @param Collection $categories @return array
entailment
protected static function familyTree(Collection $categories) : array { $ids = isset($ids) && count($ids) > 0 ? $ids : []; foreach ($categories as $category) { $ids[] = $category->id; if ($category->childrenRecursive->count() > 0) { $ids[] = static::familyTree($category->childrenRecursive); } } return $ids; }
Returns the family tree ids for the given categories. @param Collection $categories @return array
entailment
public function up() { Schema::create('products', function (Blueprint $table) { $table->increments('id'); $table->integer('category_id')->unsigned(); $table->integer('created_by')->unsigned(); $table->integer('updated_by')->unsigned()->nullable(); $table->boolean('status')->default(1); $table->enum('type', Attributes::make('type')->keys())->default('item'); $table->string('name', 100); $table->string('description', 500); $table->integer('cost'); $table->integer('price'); $table->integer('stock')->default(1); $table->integer('low_stock')->default(0); $table->string('bar_code', 100)->nullable(); $table->string('brand', 50)->nullable(); $table->enum('condition', Attributes::make('condition')->keys())->default('new'); $table->mediumText('tags')->nullable(); $table->json('features')->nullable(); $table->double('rate_val', 10, 2)->default(0)->nullable(); $table->integer('rate_count')->default(0)->nullable(); $table->integer('sale_counts')->default(0)->unsigned(); $table->integer('view_counts')->default(0)->unsigned(); $table->timestamps(); $table->foreign('created_by')->references('id')->on('users'); $table->foreign('updated_by')->references('id')->on('users'); $table->foreign('category_id')->references('id')->on('categories'); }); }
Run the migrations. @return void
entailment
public function with($data) { if (get_parent_class($data) === \Illuminate\Database\Eloquent\Model::class) { $this->data = [ 'source_id' => $data->id, 'status' => $data->status ]; } else { $this->data = $data; } return $this; }
Set the notification data. @param mixed $data @return self
entailment
public function print() : string { $label = Templates::make($this->source)->get($this->data('status')); if (is_null($label)) { return $this->defaultLabel(); } return str_replace('source_id', $this->data('source_id'), $label); }
Prints the notification label. @return string
entailment
protected function data(string $key) { if (empty($this->data[$key])) { throw new NotificationLabelsException("The [{$key}] has to be provided within the notification data."); } return $this->data[$key]; }
Returns the value for the given key. @param string $key @return mixed
entailment
protected function processNextNodeInQueue(array $exclude) { // Process the closest vertex $closest = array_search(min($this->queue), $this->queue); if (!empty($this->graph[$closest]) && !in_array($closest, $exclude)) { foreach ($this->graph[$closest] as $neighbor => $cost) { if (isset($this->distance[$neighbor])) { if ($this->distance[$closest] + $cost < $this->distance[$neighbor]) { // A shorter path was found $this->distance[$neighbor] = $this->distance[$closest] + $cost; $this->previous[$neighbor] = array($closest); $this->queue[$neighbor] = $this->distance[$neighbor]; } elseif ($this->distance[$closest] + $cost === $this->distance[$neighbor]) { // An equally short path was found $this->previous[$neighbor][] = $closest; $this->queue[$neighbor] = $this->distance[$neighbor]; } } } } unset($this->queue[$closest]); }
Process the next (i.e. closest) entry in the queue. @param string[] $exclude A list of nodes to exclude - for calculating next-shortest paths. @return void
entailment
protected function extractPaths($target) { $paths = array(array($target)); for ($key = 0; isset($paths[$key]); ++$key) { $path = $paths[$key]; if (!empty($this->previous[$path[0]])) { foreach ($this->previous[$path[0]] as $previous) { $copy = $path; array_unshift($copy, $previous); $paths[] = $copy; } unset($paths[$key]); } } return array_values($paths); }
Extract all the paths from $source to $target as arrays of nodes. @param string $target The starting node (working backwards) @return string[][] One or more shortest paths, each represented by a list of nodes
entailment
protected function parse(array $sections = []) { if (isset($sections['subject']) && ! is_null($sections['subject'])) { $this->subject = $sections['subject']; } if (isset($sections['view']) && ! is_null($sections['view'])) { $this->view = $sections['view']; } }
Parses the email information. @param array $sections
entailment
public function toMail($notifiable) { return (new MailMessage) ->subject($this->subject) ->view($this->view, [ 'name' => $notifiable->fullName, 'route' => $this->route($notifiable), ]); }
Get the mail representation of the notification. @param mixed $notifiable @return \Illuminate\Notifications\Messages\MailMessage
entailment
public function updatePreferences(string $key, $data) { $current = $this->preferences; $this->preferences = PreferencesParser::parse($current)->update($key, $data)->toJson(); $this->save(); }
Updates the user's preferences for the given key. @param string $key @param mixed $data @return void
entailment
public function markNotificationAsRead($notification_id) { $notification = $this->notifications() ->where('id', $notification_id) ->whereNull('read_at'); if ($notification->exists()) { $notification->first()->markAsRead(); } }
Marks the given notification as read. @param int $notification_id @return void
entailment
public function setPreferencesAttribute($preferences) { if (is_array($preferences)) { $preferences = json_encode($preferences); } $this->attributes['preferences'] = $preferences; }
Set the user's preferences. @param string|array $value @return void
entailment
public static function confirm(string $token, string $email) { $user = static::where('confirmation_token', $token) ->where('verified', false) ->where('email', $email) ->firstOrFail(); $user->verified = true; $user->save(); return $user; }
Confirms the user related to the given token & email. @param string $token @param string $email @return self
entailment
public function hasRole($role) { if (is_array($role)) { return in_array($this->attributes['role'], $role); } return $this->attributes['role'] == $role; }
======================================= //
entailment
public function makePetitionFor($new_email) { $petition = $this->emailChangePetitions() ->unconfirmedByEmail($new_email) ->first(); if (! is_null($petition)) { $petition->refresh(); return $petition->fresh(); } return $this->emailChangePetitions()->create([ 'expires_at' => \Carbon\Carbon::now()->addMonth(), 'old_email' => $this->email, 'new_email' => $new_email, 'token' => str_random(60), ]); }
Make a new email change petition with the given data. @param array $data @return self
entailment
public function confirmPetition(string $token, string $email) { $petition = $this->emailChangePetitions() ->unconfirmedByTokenAndEmail($token, $email) ->first(); if (! is_null($petition)) { $petition->confirmed(); } $this->email = $email; $this->save(); }
Mark a found petition by the given token and email as confirmed. @param string $token @param string $email @return void
entailment
public function default() : Company { $company = Company::where(['status' => true, 'default' => true])->first(); if (is_null($company)) { return $this->fake(); } return $company; }
Returns the default company. @return Company
entailment
public function up() { Schema::create('features', function (Blueprint $table) { $table->increments('id'); $table->string('name', 100)->unique(); $table->enum('input_type', ['text', 'select'])->default('text'); $table->enum('product_type', Attributes::make('type')->keys())->default('item'); $table->string('validation_rules', 150)->nullable(); $table->string('help_message', 150)->nullable(); $table->boolean('status')->default(1); $table->boolean('filterable')->default(0); $table->timestamps(); }); }
Run the migrations. @return void
entailment
public function index(CompanyRepository $repository, $section = null) { if (is_null($section)) { $section = 'about'; } $company = $repository->default(); abort_if(is_null($company->$section), 404); return view('about.index', [ 'tab' => $section ]); }
Loads the company about information. @param CompanyRepository $repository @param string $section @return void
entailment
protected static function boot() { parent::boot(); static::creating(function ($comment) { $comment->{$comment->getKeyName()} = Uuid::uuid4()->toString(); }); }
The model boot function. @return void
entailment
public function toDatabase($notifiable) { $labelFed = [ 'source_id' => $this->order->id, 'status' => 'new', ]; return [ 'label' => Label::make('push.comments')->with($labelFed)->print(), 'source_path' => $this->sourcePath($notifiable), 'source_id' => $this->order->id, 'status' => 'new', ]; }
Get the database representation of the notification. @param mixed $notifiable @return array
entailment
protected function sourcePath($notifiable) //while refactoring { if ($notifiable->isAdmin()) { return route('orders.show_seller_order', $this->order); } return route('orders.show_order', $this->order); }
Returns the notification path. @param mixed $notifiable @return string
entailment
public function build() { $subjectKey = 'user.emails.email_confirmation.subject'; return $this->subject($this->getSubject($subjectKey)) ->to($this->petition->new_email) ->view('emails.newEmailConfirmation', [ 'name' => Auth::user()->fullName, 'route' => $this->route(), ]); }
Build the message. @return $this
entailment
public static function bindings() { return [ Contracts\CategoryRepositoryContract::class => Categories\Repositories\CategoriesRepository::class, Contracts\FeaturesRepositoryContract::class => Features\Repositories\FeaturesRepository::class, ]; }
All of the service bindings for Antvel. @return array
entailment
public static function alias() { return [ 'category.repository' => Categories\Repositories\CategoriesRepository::class, 'category.repository.cahe' => Categories\Repositories\CategoriesCacheRepository::class, 'product.features.repository' => Features\Repositories\FeaturesRepository::class, 'product.features.repository.cahe' => Features\Repositories\FeaturesCacheRepository::class, ]; }
All of the service aliases for Antvel. @return array
entailment
protected function modelOrFind($idOrModel) { if ($idOrModel instanceof Model && $idOrModel->exists()) { return $idOrModel; } return $this->getModel()->findOrFail($idOrModel); }
Returns the given model instance. @param Model\Mixed $idOrModel @return Mixed
entailment
public function paginate($builder = null, $options = []) { $options = array_merge(['pageName' => 'page', 'columns' => ['*'], 'perPage' => null, 'page' => null ], $options); return $this->getModel() ->paginate( $options['perPage'], $options['columns'], $options['pageName'], $options['page'] ); }
Paginate the given query. @param \Illuminate\Database\Eloquent\Builder|null $builder @param array $options @return LengthAwarePaginator
entailment
public function paginateWith($loaders, $constraints = [], $paginate = []) { $categories = $this->getModel()->with($loaders); if (count($constraints) > 0) { $categories->where($constraints); } return $this->paginate($categories, $paginate); }
Paginates the given query and load relationship. @param string|array $loaders @param array $constraints @param array $paginate @return LengthAwarePaginator
entailment
public function find($constraints, $columns = '*', ...$loaders) { if (! is_array($constraints)) { $constraints = ['id' => $constraints]; } //We fetch the user using a given constraint. $model = $this->getModel()->select($columns)->where($constraints)->get(); //We throw an exception if the user was not found to avoid whether //somebody tries to look for a non-existent user. abort_if( ! $model, 404); //If loaders were requested, we will lazy load them. if (count($loaders) > 0) { $model->load(implode(',', $loaders)); } return $model; }
Find a Model in the Database using the given constraints. @param mixed $constraints @param mixed $columns @param array $loaders @return \Illuminate\Database\Eloquent\Model|null
entailment
public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('first_name', 60); $table->string('last_name', 60); $table->string('nickname', 60)->unique(); $table->string('email', 100)->unique(); $table->string('password', 60); $table->enum('role', Roles::allowed())->default(Roles::default()); $table->string('phone_number', 20)->nullable(); $table->enum('gender', ['female', 'male'])->default('male'); $table->date('birthday')->nullable(); $table->text('image')->nullable(); $table->string('facebook', 100)->nullable(); $table->string('twitter', 100)->nullable(); $table->string('website', 100)->nullable(); $table->string('language', 10)->default('en'); $table->string('time_zone', 60)->nullable(); $table->string('description', 150)->nullable(); $table->integer('rate_val')->nullable(); $table->integer('rate_count')->nullable(); $table->json('preferences')->nullable()->default(null); $table->boolean('verified')->default(false); $table->string('confirmation_token', 60)->nullable(); $table->rememberToken(); $table->timestamps(); $table->timestamp('disabled_at')->nullable(); $table->softDeletes(); }); }
Run the migrations. @return void
entailment
public function apply($constraints) : Builder { if ($constraints && $this->type == 'product_categories') { return $this->builder->whereIn('category_id', $constraints); } if ($constraints && is_array($constraints)) { return $this->filterByConstraints($constraints); } return $this->builder; }
Suggest products based on the given tags. @param array $tags @return Builder
entailment
protected function filterByConstraints($constraints) : Builder { $this->builder->where(function($query) use ($constraints) { foreach ($constraints as $filter) { if (trim($filter) != '') { $query->orWhere('tags', 'like', '%' . $filter . '%'); } } return $query; }); return $this->builder; }
Filter the query by the given constraints. @param array $constraints @return Builder
entailment
public function toDatabase($notifiable) { $labelFed = [ 'status' => $status = is_null($this->status) ? $this->order->status : $this->status, 'source_id' => $this->order->id, ]; return [ 'label' => Label::make('push.orders')->with($labelFed)->print(), 'source_path' => $this->sourcePath($notifiable), 'source_id' => $this->order->id, 'status' => $status, ]; }
Get the database representation of the notification. @param mixed $notifiable @return array
entailment
public static function decode($rules = null) { $parser = new static; if (is_string($rules) && trim($rules) !== '') { $parser->rules = Collection::make(explode('|', $rules)); } else { $parser->rules = new Collection; } return $parser; }
Creates an instance for the given rules. @param null|string $rules @return self
entailment
protected function mapRules($rules) : Collection { return Collection::make($rules) ->only($this->allowed) ->flatMap(function ($item, $key) { if ($key == 'required') { $rule[] = $item ? 'required' : ''; } else { $rule[] = $key . ':' . $item; } return $rule; }); }
Returns a collection with the given rules. @param array $rules @return Collection
entailment
public function groupWith(...$products) { $products = Collection::make($products)->flatten()->all(); foreach ($products as $product) { if (! $this->hasGroup($product)) { $this->group()->attach($product); } } }
Add products to a given group. @param array $products @return void
entailment
public function hasGroup($associated) : bool { $associated_id = $associated instanceof $this ? $associated->id : $associated; return !! $this->group()->where('associated_id', $associated_id)->exists(); }
Checks whether the given product has the associated product in its group. @param self|int $associated @return boolean
entailment
public static function image($image, $options = []) { $static = new static; $static->image = $image; $static->options = $options; $static->intervention = new ImageManager(['driver' => 'gd']); $static->normalizeNames(); return $static; }
Creates a new instance. @param string $image @param array $options @return self
entailment
protected function normalizeNames() { if (! $this->validFile($this->imagePath())) { $this->image = $this->default(); } if ($this->hasOptions()) { $this->createThumbnail(); } }
Normalizes the image name. @return void
entailment
protected function createThumbnail() { $this->thumbnail = $this->thumbnailName(); if (! $this->validFile($this->thumbnailPath())) { $img = $this->intervention ->make($this->imagePath()) ->resize($this->width(), $this->height(), function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }); $img->save($this->thumbnailPath()); } }
Creates a new thumbnail. @return void
entailment
protected function thumbnailName() { $file = explode('.', $this->image); $fileName = Arr::first($file); $fileExt = Arr::last($file); return $fileName . ($this->width() ? '_w' . $this->width() : '') . ($this->height() ? '_h' . $this->height() : '') . '.' . $fileExt; }
Returns the thumbnail name @return string
entailment
public function cast() { $image = is_null($this->thumbnail) ? $this->imagePath() : $this->thumbnailPath(); $imginfo = getimagesize($image); header('Content-type: '.$imginfo['mime']); readfile($image); }
Renders the given file. @return void
entailment
public function mock() { $image = is_null($this->thumbnail) ? $this->imagePath() : $this->thumbnailPath(); return $image; }
Returns the rendered image path for testing purposes. @return string
entailment
public function query() : Builder { if (trim($brand = $this->brand) !== '') { $this->builder->where('brand', 'LIKE', $brand); } return $this->builder; }
Builds the query with the given category. @return Builder
entailment
public function handle($request, Closure $next, $guard = null) { $user = $request->user(); if ($this->isAuthorized($user)) { return $next($request); } abort(401); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param Closure $next @param string|null $guard @return mixed
entailment
protected function resolveQuery() : callable { return function($query) { foreach ($this->features as $key => $feature) { $query->orWhere('features->' . $key, urldecode($feature)); } }; }
Resolve the query for the requested features. @return callable
entailment
public function filterableValidationRules() : array { return $this->filterable()->filter(function ($item) { return trim($item->validation_rules) != '' && ! is_null($item->validation_rules); })->mapWithKeys(function ($item) { return ['features.' . $item->name => $item->validation_rules]; })->all(); }
Returns an array with the validation rules for the filterable features. @return array
entailment
public static function make(string $attr) { $attributes = new static; if (! method_exists($attributes, $attr)) { throw new \RuntimeException("The attribute {$attr} does not exist in the product object attributes"); } $attributes->attribute = $attributes->$attr(); return $attributes; }
Creates a new instance. @param string $attr @return self
entailment
public function handle(FeatureNameWasUpdated $event) { $attributes = Parser::replaceTheGivenKeyFor( $products = $this->products($event->feature->name), $event->feature->name, $event->updatedName ); $this->updateProductsFeatures( $attributes, $products ); $event->feature->update(['name' => $event->updatedName]); }
Handle the event. @param FeatureNameWasUpdated $event @return void
entailment
protected function updateProductsFeatures(array $attributes, $products) { $products->each(function ($item, $key) use ($attributes, $products) { $item->update(['features' => json_encode($attributes[$item->id])]); $item->save(); }); }
Update the given products features with the passed attributes. @param array $attributes @param \Illuminate\Database\Eloquent\Collection $products @return void
entailment
public function shoppingCart() { $shoppingCart = $this->orders()->with('details') ->where('type', 'cart') ->first(); return is_null($shoppingCart) ? collect() : $shoppingCart->details; }
The user's shopping cart. | while refactoring @return mixed
entailment
public function send(string $notifiable, Notification $notification) { $channelResult = $notification->toMail($notifiable); $messages = is_array($channelResult) ? $channelResult : [$channelResult]; foreach ($messages as $message) { if (! $message instanceof Message) { throw new \Exception("Message needs to be an instance of craft\mail\Message"); } $message->send(); } }
Send the given notification. @param string $notifiable @param Notification $notification @return void @throws \Exception
entailment
public function store(CategoriesRequest $request) { $category = Category::create( $request->all() ); return redirect()->route('categories.edit', $category)->with( 'status', trans('globals.success_text') ); }
Stores a new category. @param CategoriesRequest $request @return void
entailment
public function edit(Category $category) { return view('dashboard.sections.categories.edit', [ 'hasParent' => ! is_null($category->parent), 'parents' => Category::parents()->get(), 'category' => $category->load('parent'), ]); }
Edits a given category. @param Category $category @return void
entailment
public function update(CategoriesRequest $request, Category $category) { $category->update( $request->all() ); return redirect()->route('categories.edit', $category)->with( 'status', trans('globals.success_text') ); }
Updates the given category. @param CategoriesRequest $request @param Category $category @return void
entailment
protected function parseRequest(array $request) : array { $request = Collection::make($request); $allowed = $request->filter(function ($item) { return trim($item) != ''; })->only(array_keys($this->allowed)); if ($filterable = $this->allowedFeatures($request)) { $allowed['features'] = $filterable; } return $allowed->all(); }
Parses the incoming request. @param array $request @return array
entailment
public function allowedFeatures(Collection $request) : array { return $request->filter(function ($item, $key) { return trim($item) != '' && $this->isFilterable($key); })->all(); }
Returns an array with the allowed features. @param Collection $request @return array
entailment
public function apply(Builder $builder) : Builder { if ($this->hasRequest()) { foreach ($this->request as $filter => $value) { $this->resolveQueryFor($builder, $filter); } } return $builder; }
Apply an eloquent query to a given builder. @param Builder $builder @return Builder
entailment
protected function resolveQueryFor(Builder $builder, string $filter) : Builder { $factory = $this->allowed[$filter]; $input = $this->wantsByPrices($filter) ? $this->prices() : $this->request[$filter]; return (new $factory($input, $builder))->query(); }
Returns a query filtered by the given filter. @param Builder $builder @param string $key @return Builder
entailment
public function index(Request $request) { //I need to come back in here and check how I can sync the paginated products //with the filters. The issue here is paginated does not contain the whole //result, therefore, the filters count are worng. $products = $this->products->filter( $request->all() ); // this line is required in order for the store to show // the counter on the side bar filters. $allProducts = $products->get(); if (Auth::check()) { Auth::user()->updatePreferences('my_searches', $allProducts); } return view('products.index', [ 'suggestions' => Suggestions\Suggest::shakeFor($allProducts), 'refine' => Parsers\Breadcrumb::parse($request->all()), 'filters' => Parsers\Filters::parse($allProducts), 'products' => $products->paginate(28), 'panel' => $this->panel, ]); }
Loads the foundation dashboard. @return void
entailment
public function indexDashboard(Request $request) { $products = $this->products->filter($request->all()) ->with('creator', 'updater') ->paginate(20); return view('dashboard.sections.products.index', [ 'products' => $products, ]); }
List the seller products. @return void
entailment
public function show(Product $product) { $product->load('group', 'category'); //increasing product counters, in order to have a suggestion orden (new ProductsRepository)->increment('view_counts', $product); //saving the product tags into users preferences if (trim($product->tags) != '' && auth()->check()) { auth()->user()->updatePreferences('product_viewed', $product->tags); } return view('products.detailProd', [ 'suggestions' => Suggestions\Suggest::for('product_viewed')->shake()->get('product_viewed'), 'reviews' => OrderDetail::ReviewsFor($product->id), 'allWishes' => Order::forSignedUser('wishlist'), 'features' => Feature::filterable()->get(), 'product' => $product, ]); }
Display the given product. @param Product $product @return void
entailment
public function create(Feature $features) { return view('dashboard.sections.products.create', [ 'conditions' => Attributes::make('condition')->get(), 'features' => $features->filterable()->get(), 'categories' => Category::actives()->get(), 'MAX_PICS' => Images::MAX_PICS, ]); }
Show the creating form. @param Feature $features @return void
entailment
public function store(ProductsRequest $request) { $product = $this->products->create( $request->all() ); return redirect()->route('items.edit', [ 'item' => $product->id ])->with('status', trans('globals.success_text')); }
Stores a new product. @param ProductsRequest $request @return void
entailment
public function edit(Models\Product $item, Feature $features) { return view('dashboard.sections.products.edit', [ 'MAX_PICS' => Images::MAX_PICS - $item->pictures->count(), 'conditions' => Attributes::make('condition')->get(), 'features' => $features->filterable()->get(), 'categories' => Category::actives()->get(), 'item' => $item, ]); }
Show the editing form. @param Models\Product $item @param Feature $features @return void
entailment
public function update(ProductsRequest $request, $item) { $this->products->update( $request->all(), $item ); return back()->with('status', trans('globals.success_text')); }
Updates the given product. @param ProductsRequest $request @param integer $item @return void
entailment