sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function rules() { return [ 'description' => 'required|max:100', '_pictures_file' => [ 'mimes:jpeg,png,jpg', Rule::dimensions()->maxWidth(1000)->maxHeight(500) ], 'name' => [ 'required', Rule::unique('categories')->ignore($this->request->get('current_category')), ], ]; }
Validation rules. @return array
entailment
public function query() : Builder { if (trim($conditions = $this->conditions) !== '') { $this->builder->where('condition', 'LIKE', $conditions); } return $this->builder; }
Builds the query with the given category. @return Builder
entailment
public function query() : Builder { if (! is_null($this->min) && ! is_null($this->max)) { $this->builder->whereBetween('price', [$this->min, $this->max]); } if (! is_null($this->min) && is_null($this->max)) { $this->builder->where('price', '>=', $this->min); } if (is_null($this->min) && ! is_null($this->max)) { $this->builder->where('price', '<=', $this->max); } return $this->builder; }
Builds the query with the given category. @return Builder
entailment
private function extractSnakes(array $v_save, $x, $y) { $snakes = array(); for ($d = count($v_save) - 1; $x >= 0 && $y >= 0; $d--) { array_unshift($snakes, array($x, $y)); $v = $v_save[$d]; $k = $x - $y; if ($k === -$d || $k !== $d && $v[$k - 1] < $v[$k + 1]) { $k_prev = $k + 1; } else { $k_prev = $k - 1; } $x = $v[$k_prev]; $y = $x - $k_prev; } return $snakes; }
Backtrack through the intermediate results to extract the "snakes" that are visited on the chosen "D-path". @param string[] $v_save Intermediate results @param int $x End position @param int $y End position @return int[][]
entailment
private function formatSolution(array $snakes, array $a, array $b) { $solution = array(); $x = 0; $y = 0; foreach ($snakes as $snake) { // Horizontals while ($snake[0] - $snake[1] > $x - $y) { $solution[] = array($a[$x], self::DELETE); $x++; } // Verticals while ($snake[0] - $snake[1] < $x - $y) { $solution[] = array($b[$y], self::INSERT); $y++; } // Diagonals while ($x < $snake[0]) { $solution[] = array($a[$x], self::KEEP); $x++; $y++; } } return $solution; }
Convert a list of "snakes" into a set of insert/keep/delete instructions. @param integer[][] $snakes Common subsequences @param string[] $a First sequence @param string[] $b Second sequence @return array[] - pairs of token and edit (-1 for delete, 0 for keep, +1 for insert)
entailment
public function calculate(array $a, array $b) { // The algorithm uses array keys numbered from zero. $n = count($a); $m = count($b); $a = array_values($a); $b = array_values($b); $max = $m + $n; // Keep a copy of $v after each iteration of $d. $v_save = array(); // Find the shortest "D-path". $v = array(1 => 0); for ($d = 0; $d <= $max; $d++) { // Examine all possible "K-lines" for this "D-path". for ($k = -$d; $k <= $d; $k += 2) { if ($k === -$d || $k !== $d && $v[$k - 1] < $v[$k + 1]) { // Move down. $x = $v[$k + 1]; } else { // Move right. $x = $v[$k - 1] + 1; } // Derive Y from X. $y = $x - $k; // Follow the diagonal. while ($x < $n && $y < $m && $a[$x] === $b[$y]) { $x++; $y++; } // Just store X, as we can calculate Y (from X + K). $v[$k] = $x; $v_save[$d] = $v; // Solution found? if ($x === $n && $y === $m) { break 2; } } } // Extract the solution by back-tracking through the saved results. $snakes = $this->extractSnakes($v_save, $n, $m); // Format the snakes as a set of instructions. return $this->formatSolution($snakes, $a, $b); }
Calculate the shortest edit sequence to convert $x into $y. @param string[] $a - tokens (characters, words or lines) @param string[] $b - tokens (characters, words or lines) @return array[] - pairs of token and edit (-1 for delete, 0 for keep, +1 for insert)
entailment
public function respondsWithSuccess(string $message, string $redirectTo = '') { return response()->json([ 'redirectTo' => $redirectTo, 'callback' => $redirectTo, 'message' => $message, 'success' => true, ], 200); }
Return a success JSON response. @param string $message @param string $redirectTo @return JSON
entailment
public function findConnectedComponents() { // Find the first unallocated node $node = array_search(0, $this->nodes, true); while ($node !== false) { // Find the next connected-component. $this->component++; $this->depthFirstSearch($node, $this->component); // Find the next unallocated node. $node = array_search(0, $this->nodes, true); } return $this->groupResults(); }
An array of components (arrays). @return array
entailment
private function groupResults() { $result = array(); foreach ($this->nodes as $node => $component) { if (array_key_exists($component, $result)) { $result[$component][] = $node; } else { $result[$component] = array($node); } } return $result; }
Group the nodes by component. @return array
entailment
private function depthFirstSearch($node, $component) { $this->nodes[$node] = $component; foreach (array_keys($this->graph[$node]) as $next) { if ($this->nodes[$next] === 0) { $this->depthFirstSearch($next, $component); } } }
Find all nodes connected to $node and mark them as part of component $component. @param $node @param $component
entailment
public function edit(Request $request, Product $itemgroup) { $listing = $this->products->filter($request->all()); return view('dashboard.sections.products.grouping.edit', [ 'getQueryString' => trim($request->getQueryString()) != '' ? $request->getQueryString() . '&' : '', 'filters' => Parsers\Filters::parse($listing->get()), 'groupingIds' => $itemgroup->group->pluck('id'), 'listing' => $listing->paginate(25), 'product' => $itemgroup, ]); }
Edits the given product grouping. @param Request $request @param Product $itemgroup @return void
entailment
public function update(Request $request, Product $itemgroup) { $itemgroup->groupWith( $request->get('associates') ); return redirect() ->route('itemgroup.edit', $itemgroup) ->with('status', trans('globals.success_text')); }
Updates the given product grouping. @param Request $request @param Product $itemgroup @return void
entailment
public function send($notifiable, Notification $notification) { $message = $notification->toSlack(); $this->http->post($notifiable, $this->buildJsonPayload($message)); }
Send the given notification. @param mixed $notifiable @param Notification $notification
entailment
protected function attachments(SlackMessage $message) { return collect($message->attachments)->map(function ($attachment) use ($message) { return array_filter([ 'color' => $attachment->color ?: $message->color(), 'title' => $attachment->title, 'text' => $attachment->content, 'fallback' => $attachment->fallback, 'title_link' => $attachment->url, 'fields' => $this->fields($attachment), 'mrkdwn_in' => $attachment->markdown, 'footer' => $attachment->footer, 'footer_icon' => $attachment->footerIcon, 'ts' => $attachment->timestamp, ]); })->all(); }
Format the message's attachments. @param SlackMessage $message @return array
entailment
protected function normalizeProvider(ConfigRepository $config) : string { $default = $config->get('auth.providers.users.model'); if (is_null($default) || trim($default) == '') { return \Antvel\Users\Models\User::class; } return $default; }
Normalize the authentication provider class name. @param ConfigRepository $config @return string
entailment
public function handle(NotificationSent $event) { if (! is_null($event->response) && $event->response->notifiable_type !== $this->userModelProvider) { $event->response->notifiable_type = $this->userModelProvider; $event->response->save(); } }
Handle the event. @param NotificationSent $event @return void
entailment
public function handle(ProfileWasUpdated $event) { if ($event->petition) { $this->mailer->send(new NewEmailConfirmation($event->petition)); } }
Handle the event. @param ProfileWasUpdated $event @return void
entailment
public function categoriesWithProducts(array $request = [], $limit = 10, $columns = '*') { $key = md5(vsprintf('%s', ['categories_with_products'])); return Cache::remember($key, 25, function () use ($request, $limit, $columns) { return $this->next->categoriesWithProducts($request, $limit, $columns); }); }
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 = 'id') { $key = md5(vsprintf('%s', ['children_of_category'])); return Cache::remember($key, 25, function () use ($category_id, $limit, $columns) { return $this->next->childrenOf($category_id, $limit, $columns); }); }
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 store(FeaturesRequest $request) { $feature = Feature::create($request->all()); return redirect()->route('features.edit', $feature)->with('status', trans('globals.success_text')); }
Stores a new feature. @param FeaturesRequest $request @return void
entailment
public function edit(Feature $feature) { return view('dashboard.sections.features.edit', [ 'validation_rules' => ValidationRulesParser::decode($feature->validation_rules)->all(), 'allowed_rules' => ValidationRulesParser::allowed(), 'feature' => $feature, ]); }
Edits a given category. @param Feature $feature @return void
entailment
public function update(FeaturesRequest $request, Feature $feature) { if ($request->has('name') && $feature->name != $request->get('name')) { event(new FeatureNameWasUpdated($feature, $request->get('name'))); } $feature->update( $request->except('name') ); return redirect()->route('features.edit', $feature)->with('status', trans('globals.success_text')); }
Updates the given feature. @param FeaturesRequest $request @param Feature $feature @return void
entailment
public function updatePictures($pictures) { foreach ($pictures as $picture) { $image = $this->pictures()->where('id', $picture['id']); if ($image->exists()){ $image->update(['path' => $picture['path']]); } else { $this->pictures()->create(['path' => $picture['path']]); } } }
Update the model pictures. @param array $pictures @return array
entailment
public function deletePictures($ids) { $pictures = $this->pictures()->whereIn('id', $ids)->get(); $pictures->each(function ($item) { $item->delete(); }); }
Deletes the given pictures from the model. @param array $ids @return void
entailment
public function updateDefaultPicture($pictureId) { if ($pictureId) { $this->pictures()->update(['default' => false]); $this->pictures()->where('id', $pictureId)->update(['default' => true]); } }
Updates the given product default picture. @param integer $pictureId @return void
entailment
public function getDefaultPictureAttribute() { $default = $this->pictures->where('default', true)->first(); if ($default) { return $default->path; } $picture = $this->pictures->first(); if (is_null($picture)) { return 'images/no-image.jpg'; } return $picture->path; }
Returns the product default picture. @return string
entailment
public function init() { parent::init(); self::$plugin = $this; // Add in our console commands if (Craft::$app instanceof ConsoleApplication) { $this->controllerNamespace = 'rias\notifications\console\controllers'; } // Register our variables Event::on( CraftVariable::class, CraftVariable::EVENT_INIT, function (Event $event) { /** @var CraftVariable $variable */ $variable = $event->sender; $variable->set('notifications', NotificationsVariable::class); } ); // Register the events for each Notification that's configured foreach ($this->getSettings()->notifications as $notificationSettings) { Event::on( $notificationSettings['class'], $notificationSettings['event'], function (Event $event) use ($notificationSettings) { /* @var Notification $notification */ $notification = $notificationSettings['notification']; Notifications::$plugin->notificationsService->send( new $notification(['event' => $event]) ); } ); } }
Set our $plugin static property to this class so that it can be accessed via Notifications::$plugin Called after the plugin class is instantiated; do any one-time initialization here such as hooks and events. If you have a '/vendor/autoload.php' file, it will be loaded for you automatically; you do not need to load it in your init() method.
entailment
public function refresh() { $this->expires_at = Carbon::now()->addMonth(); $this->token = str_random(60); $this->save(); }
Refresh a given petition. @return void
entailment
public function confirmed() { $this->confirmed = true; $this->confirmed_at = Carbon::now(); $this->save(); }
Confirm a given petition. @return void
entailment
public function scopeUnconfirmedByTokenAndEmail($query, string $token, string $email) { return $query->where('expires_at', '>=', Carbon::now()) ->where('new_email', $email) ->where('confirmed', false) ->where('token', $token); }
Retrieve a petition by the given token and email address. @param Illuminate\Database\Eloquent\Builder $query @param string $token @param string $email @return Illuminate\Database\Eloquent\Builder
entailment
protected function normalizeBag($bag) : Collection { return Collection::make($bag)->filter(function ($item) { return is_string($item) ? trim($item) !== '' : $item; }); }
Normalize the given bag. @param array\null $bag @return Collection
entailment
protected function files() : Collection { $storing = $this->pictures->get('storing'); return $this->normalizeBag( is_array($storing) ? $storing : [$storing] ); }
Returns the new files. @return Collection
entailment
public function store() : array //check whether this method is required, otherwise, we have to rename to delte { $this->validate(); if ($this->files()->isEmpty()) { return []; } return $this->files()->flatMap(function ($item) { $files[] = ['path' => $item->store($this->directory)]; return $files; })->all(); }
Store the given pictures. @return array
entailment
public function update($current) { $this->validate(); if ($this->files()->isEmpty()) { return $this->currentPictures($current); } $result = $this->mapUpdatedPictures($current); if (count($result) == 1 && is_array($result[0])) { return $result[0]; } return $result; }
Update the given pictures. @param Collection $current @return string|array
entailment
protected function currentPictures($current) { if (is_string($current) || is_null($current) || count($current) == 0){ return ['id' => null, 'path' => $current]; } return $current->map(function ($item) { $array = [ 'id' => $item['id'], 'path' => $item['path'] ]; return $array; })->all(); }
Map the current pictures. @param array $current @return array
entailment
protected function mapUpdatedPictures($current) { $this->deleteCurrentFiles($current); return $this->files()->flatMap(function ($item, $key) { $files[] = [ 'id' => $key, 'path' => $item->store($this->directory) ]; return $files; })->all(); }
Map the updated pictures. @param $current Collection @return string|array
entailment
public function delete($current) { if (is_string($current)) { return $this->deleteCurrentFiles($current); } $toDelete = $this->deleting()->keys()->all(); $this->deleteCurrentFiles( $current->whereIn('id', $toDelete) ); return $toDelete; }
Deletes the given pictures. @param Collection $current @return array|bool
entailment
protected function deleteCurrentFiles($current) { $current = $current instanceof Collection ? $current : Collection::make($current); $files = $current->pluck('path'); //if the current value is string, it means that we are dealing with one //file instead with an array of them. So, we have to make sure to add //it to the final collection in order for it to be deleted. if (is_string($current->first())) { $files->push($current->first()); } Storage::delete($files->all()); $this->deleteRelatedFiles($files); }
Deletes the given pictures. @param array\Collection $current @return void
entailment
protected function deleteRelatedFiles($deleting) { $files = $this->deletingFilesNamesList($deleting); foreach ($files as $file) { foreach (Storage::files($this->directory) as $relative) { if (strpos($relative, $file) !== false) { Storage::delete($relative); } } } }
Delete the files related to the ones to be delete. @param Collection $deleting @return void
entailment
protected function deletingFilesNamesList($files) : array { return $files->flatMap(function($item) { $path_parts = pathinfo($item); $result[] = $path_parts['filename']; return $result; })->filter(function($item) { return trim($item) != ''; })->all(); }
Returns a sanitized deleting files list. @param Collection $files @return array
entailment
protected function all() : array { return array_merge([ 'category' => $this->forCategories(), 'brands' => array_count_values($this->products->pluck('brand')->all()), 'conditions' => array_count_values($this->products->pluck('condition')->all()), ], $this->forFeatures()); }
Returns the parsed filters. @return array
entailment
protected function forCategories() : array { $categories = $this->products->pluck('category'); return $categories->mapWithKeys(function ($item) use ($categories) { $result[$item->id] = [ 'id' => $item->id, 'name' => $item->name, 'qty' => $categories->where('id', $item->id)->count() ]; return $result; })->all(); }
Parses the category filter. @return array
entailment
protected function forFeatures() : array { return Collection::make($this->allowed)->mapWithKeys(function ($feature) { return [ $feature => array_count_values($this->features()[$feature]) ]; })->all(); }
Returns the mapped features with their quantities. @return array
entailment
protected function features() : array { $features = $this->products->pluck('features'); return Collection::make($this->allowed)->mapWithKeys(function ($allowed) use ($features) { return [ $allowed => $features->pluck($allowed)->filter(function ($allowed) { return ! is_null($allowed); })->all() ]; })->all(); }
Returns a map with the given features. @return array
entailment
public function confirmEmail(string $token, string $email) { Auth::user()->confirmPetition($token, $email); Auth::logout(); return redirect()->route('user.index'); }
Confirms the users's new email address. @param string $token @param string $email @return void
entailment
public function update(string $action) { $action = mb_strtolower($action); if (! in_array($action, ['enable', 'disable'])) { return $this->respondsWithError(trans('globals.action_not_allowed')); } Auth::user()->$action(); return $this->respondsWithSuccess(trans('user.success')); }
Update user's profile with a given action. @param string $action @return void
entailment
public function store(Request $request, CompanyRepository $repository) { $data = $request->validate([ 'name' => 'required', 'email' => 'required|email', 'message' => 'required' ]); $company = $repository->default(); Mail::to($company->email)->send(new SendContactEmail($company, $data)); return redirect() ->route('contact') ->with('message', trans('company.contact.message')); }
Sends the contact us email. @param Request $request @param CompanyRepository $repository @return void
entailment
public function up() { Schema::create('companies', function (Blueprint $table) { $table->increments('id'); $table->integer('company_id')->unsigned()->nullable(); $table->boolean('default')->default(0); //Profile information $table->string('name', 100); $table->longText('description'); $table->string('email', 100)->unique(); $table->string('logo', 100)->nullable(); $table->string('slogan', 100)->nullable(); $table->boolean('status')->default(1); //Contact information $table->string('contact_email', 100)->unique(); $table->string('sales_email', 100)->unique(); $table->string('support_email', 100)->unique(); $table->string('phone_number', 20)->nullable(); $table->string('cell_phone', 20)->nullable(); $table->string('address', 100)->nullable(); $table->string('state', 100)->nullable(); $table->string('city', 100)->nullable(); $table->string('zip_code', 20)->nullable(); //Social information $table->string('website', 150); $table->string('twitter', 100)->nullable(); $table->string('facebook', 100)->nullable(); //SEO information $table->longText('keywords'); //CMS information $table->mediumText('about'); $table->mediumText('terms'); $table->mediumText('refunds'); $table->timestamps(); $table->softDeletes(); }); }
Run the migrations. @return void
entailment
public function send(Notification $notification) { $original = clone $notification; foreach ($notification->via() as $channel => $notifiables) { $notifiables = $this->formatNotifiables($notifiables); foreach ($notifiables as $notifiable) { $notificationId = Uuid::uuid4()->toString(); $notification = clone $original; if (! $notification->id) { $notification->id = $notificationId; } if (! $this->shouldSendNotification($notifiable, $notification, $channel)) { continue; } $response = $this->channel($channel)->send($notifiable, $notification); $event = new SendEvent([ 'notification' => $notification, 'notifiable' => $notifiable, 'channel' => $channel, 'response' => $response, ]); $this->trigger(self::EVENT_AFTER_SEND, $event); } } }
Send the given notification to the given notifiable entities. @param Notification $notification @return void
entailment
public function getAllUnread(User $user = null) { // If there's no passed user, get the current logged in user $user = $user ?? Craft::$app->getUser(); if ($user) { $notifications = NotificationsRecord::find()->where(['notifiable' => $user->id, 'read_at' => null])->all(); return $this->formatNotificationData($notifications)->toArray(); } // No notifications when we don't have a passed in or logged in user return []; }
Get all unread notifications for a certain User @param User $user @return array
entailment
public function markAsRead($notifications = null) { // If we don't pass notifications, mark all as read for the current logged in user $user = Craft::$app->getUser(); if ($user && is_null($notifications)) { $notifications = NotificationsRecord::find()->where(['notifiable' => $user->getId()])->all(); } // Make sure we have a collection to loop over $notifications = collect($notifications); $notificationIds = $notifications->map(function ($notification) { return is_object($notification) ? $notification->id : $notification; }); // Update the read notifications if (! is_null($notificationIds)) { $now = DateTimeHelper::currentUTCDateTime()->format('Y-m-d H:i:s'); NotificationsRecord::updateAll(['read_at' => $now], ['id' => $notificationIds]); } }
Mark a notification as read @param $notifications
entailment
protected function formatNotificationData($notifications) { return collect($notifications)->map(function ($notification) { $notification->data = json_decode($notification->data); return $notification; }); }
Decode notification data @param $notifications @return \Illuminate\Support\Collection
entailment
protected function shouldSendNotification($notifiable, $notification, $channel) { $event = new SendEvent([ 'notification' => $notification, 'notifiable' => $notifiable, 'channel' => $channel, ]); $this->trigger(self::EVENT_BEFORE_SEND, $event); return $event->sendNotification; }
Determines if the notification can be sent. @param mixed $notifiable @param Notification $notification @param string $channel @return bool
entailment
protected function formatNotifiables($notifiables) { // Notifiables can be an anonymous function that returns an array if (is_callable($notifiables)) { $notifiables = $notifiables(); } // Always make sure we have an array if (! is_array($notifiables)) { return [$notifiables]; } return $notifiables; }
Format the notifiables into an array if necessary. @param mixed $notifiables @return array
entailment
protected function channel($name = null) { if (!isset(self::channels()[$name])) { throw new InvalidCallException("No channel {$name} exists."); } return call_user_func(self::channels()[$name]); }
Get a channel instance. @param string|null $name @return mixed
entailment
public function unread($limit = 5) { $unread = Auth::user()->unreadNotifications->take($limit); return $unread->map(function ($item) { return $this->toCollect($item); }); }
Shows the unread user notifications formatted. @param int $limit @return array
entailment
public function read($limit = 5) { $read = Auth::user()->notifications()->whereNotNull('read_at')->take($limit)->get(); return $read->map(function ($item) { return $this->toCollect($item); }); }
Shows the read user notifications formatted. @param int $limit @return array
entailment
public function all($limit = 5) { $all = Auth::user()->notifications->take($limit); return $all->map(function ($item) { return $this->toCollect($item); }); }
Shows the read user notifications formatted. @param int $limit @return array
entailment
protected function toCollect($notification) : Collection { return Collection::make([ 'hasBeenRead' => ! is_null($notification->read_at), 'path' => $notification->data['source_path'], 'label' => $notification->data['label'], 'id' => $notification->id, ]); }
Formats the given notification to the desired array. @param mixed $notification @return array
entailment
public function handle(ProfileWasUpdated $event) { //If the user requested a new email address, we create a new email change //petition record in the database and send out a confirmation email. if ($continuePropagation = $this->emailWasChanged($event)) { $this->createNewEmailPetition($event); } $this->updateUserPorfile($event->request); //The event propagation will continue as long as the user changed his email address. return $continuePropagation; }
Handle the event. @param ProfileWasUpdated $event @return void
entailment
protected function emailWasChanged(ProfileWasUpdated $event) : bool { $newEmail = $event->request->get('email'); return ! is_null($newEmail) && $newEmail != Auth::user()->email; }
Checks whether the user changed his email address. @param ProfileWasUpdated $event @return bool
entailment
protected function createNewEmailPetition(ProfileWasUpdated $event) { $event->petition = Auth::user()->makePetitionFor($event->request['email']); //By selecting a new email address users have to confirm their new selection //in order for them to use it as their new email account. Therefore, //we will not update the given user email address until he //confirms it through his new email account. unset($event->request['email']); }
Creates a new email petition. @param ProfileWasUpdated $event @return void
entailment
protected function updateUserPorfile($data) { $data = $data->except('email'); if ($data instanceof Collection) { $data = $data->toArray(); } if (isset($data['password'])) { $data['password'] = Hash::make($data['password']); } Auth::user()->update($data); }
Updates the user profile with the given data. @param \Illuminate\Http\Request|Collection $data @return void
entailment
public function shake() { return $this->keys->flatMap(function ($preferenceKey) { $products[$preferenceKey] = is_string($preferenceKey) ? $this->suggestFor($preferenceKey) : new Collection; return $products; }); }
Returns a mapped products suggestions based on the given key. @param Collection $products @return Collection
entailment
public static function shakeFor(Collection $products) : Collection { $suggestions = new static($key = 'all'); $suggestions->products = $products; $suggestions->excluding($products); return $suggestions->suggestFor($key); }
Returns a mapped products suggestions based on the given products. @param Collection $products @return Collection
entailment
public function excluding(Collection $products) { $ids = $products->pluck('id'); if ($this->excluding->count() == 0) { $this->excluding = $ids; } else { foreach ($ids as $id) { $this->excluding->push($id); } } return $this; }
Builds the excluding list based on the given collection. @param Collection $products @return void
entailment
protected function suggestFor(string $preferenceKey) : Collection { $suggestions = Product::suggestionsFor($preferenceKey, $this->resolveTagsFor($preferenceKey)) ->whereNotIn('id', $this->excluding->all()) ->orderBy('rate_val', 'desc') ->take($this->limit) ->get(); if ($suggestions->count() < $this->limit) { $suggestions = $suggestions->merge($this->completeWithRandomProducts($suggestions)); } $this->excluding($suggestions); return $suggestions; }
Returns a products suggestion for the given key. @param string $preferenceKey @return Collection
entailment
protected function completeWithRandomProducts(Collection $products) : Collection { $currentLimit = $this->limit - $products->count(); return Product::whereNotIn('id', $this->excluding->all()) ->orderBy('rate_val', 'desc') ->take($currentLimit) ->get(); }
Completes the returned suggestion with random products. @param Collection $products @return Collection
entailment
protected function resolveTagsFor(string $preferenceKey) : array { if (! is_null($this->products)) { return $this->pullTagsFromProducts(); } $preferences = $this->resolveUserPreferences(); $tags = PreferencesParser::parse($preferences)->all($this->keys); return isset($tags[$preferenceKey]) ? $tags[$preferenceKey] : []; }
Resolves the tags list for the given key. @param string $preferenceKey @return array
entailment
protected function pullTagsFromProducts() : array { return $this->products->map(function ($item) { return explode(',', str_replace('"', '', $item->tags)); })->flatten()->unique()->all(); }
Returns an array with tags extracted from the products list. @return array
entailment
protected function resolveUserPreferences() { if ($this->user) { return $this->user->preferences; } if (Auth::check()) { return Auth::user()->preferences; } return null; }
Resolve the user's preferences tags. @return null/array
entailment
public function update(ProfileRequest $request, User $user) { event(new ProfileWasUpdated($request)); if ($request->wantsJson()) { return $this->respondsWithSuccess('ok'); } return back(); }
Updates the user profile. @param ProfileRequest $request @param User $user @return void
entailment
protected function resolve() { $key = $this->templatesFile . '.' . $this->source; if (Lang::has($key)) { return Lang::get($key); } return $this->default(); }
Resolves the notification resources. @return array
entailment
public function default() { $file = Antvel::langPath() . DIRECTORY_SEPARATOR . "en" . DIRECTORY_SEPARATOR . $this->templatesFile . ".php"; $templates = (new Filesystem)->getRequire($file); return Arr::get($templates, $this->source); }
Returns the default notifications resources. @return array
entailment
public function authorize() : bool { return Auth::check() && Auth::user()->is($this->user()) && $this->isAllowed(); }
Determine if the user is authorized to make this request. @return bool
entailment
protected function isAllowed() : bool { return $this->request->has('referral') && in_array($this->request->get('referral'), $this->allowedReferral); }
Checks whether the referral form is allowed to make the incoming request. @return bool
entailment
public function rules() : array { $referral = mb_strtolower($this->request->get('referral') ?? 'profile'); $resolver = 'rulesFor' . ucfirst($referral); return $this->$resolver(); }
Resolves the validation rules for a given referral form. @return array
entailment
protected function rulesForProfile() : array { return [ 'first_name' => 'required', 'last_name' => 'required', 'gender' => 'required', 'email' => [ Rule::unique('users')->ignore(Auth::user()->id), 'required', 'email', ], 'nickname' => [ Rule::unique('users')->ignore(Auth::user()->nickname, 'nickname'), 'required', 'max:20', ], 'pictures.storing' => [ Rule::dimensions()->maxWidth(500)->maxHeight(500), 'mimes:jpeg,png,jpg', 'image', ], ]; }
Returns validation rules for the form profile. @return array
entailment
public function create(array $attributes) { $attributes = Collection::make($attributes); $attr = $attributes->except('features', 'pictures')->merge([ 'features' => \Antvel\Features\Parser::toJson($attributes->get('features')), 'category_id' => $attributes->get('category'), 'price' => $attributes->get('price') * 100, 'cost' => $attributes->get('cost') * 100, 'status' => $attributes->get('status'), 'created_by' => auth()->user()->id, 'updated_by' => auth()->user()->id, 'tags' => $attributes->get('name'), ])->all(); $product = Product::create($attr); $this->createPicturesFor($product, $attributes); return $product; }
Save a new model and return the instance. @param array $attributes @return \Illuminate\Database\Eloquent\Model
entailment
public function update(array $attributes, $idOrModel, array $options = []) { $product = $this->modelOrFind($idOrModel); $attributes = Collection::make($attributes); $attr = $attributes->except('features', 'pictures', 'default_picture')->merge([ 'features' => \Antvel\Features\Parser::toJson($attributes->get('features')), 'category_id' => $attributes->get('category'), 'price' => $attributes->get('price') * 100, 'cost' => $attributes->get('cost') * 100, 'status' => $attributes->get('status'), 'updated_by' => auth()->user()->id, 'tags' => $attributes->get('name'), ])->all(); $this->updatePicturesFor($product, $attributes); return $product->update($attr); }
Update a Model in the database. @param array $attributes @param Product|mixed $idOrModel @param array $options @return bool
entailment
public function filter($request = [], $limit = null) { return $this->getModel() ->with('category') ->actives() //it needs to go into the query object as well ->filter($request) ->orderBy('rate_val', 'desc'); }
Filters products by a given request. @param array $request @param integer $limit @return \Illuminate\Database\Eloquent\Collection
entailment
protected function registerServices() { foreach (Antvel::bindings() as $key => $value) { is_numeric($key) ? $this->app->singleton($value) : $this->app->singleton($key, $value); } }
Register Antvel services in the container. @return void
entailment
protected function registerServicesAliases() { foreach (Antvel::alias() as $key => $value) { $this->app->alias($value, $key); } }
Register Antvel services aliases in the container. @return void
entailment
protected function rulesForBody() { return [ 'name' => 'required', 'description' => 'required', 'cost' => 'required|numeric|max:999999999', 'price' => 'required|numeric|max:999999999', 'brand' => 'required', 'stock' => 'required|integer', 'low_stock' => 'required|integer', 'status' => 'required|boolean', 'category' => [ 'required', Rule::exists('categories', 'id')->where('id', $this->request->get('category')), ], 'condition' => [ 'required', Rule::in(Attributes::make('condition')->keys()), ], ]; }
Builds the validation rules for the product information. @return array
entailment
protected function forPictures() : array { $pictures = Collection::make($this->all())->filter(function($item, $key) { return $key == 'pictures'; })->get('pictures'); if (is_null($pictures) || empty($pictures['storing'])) { return []; } return Collection::make($pictures['storing'])->mapWithKeys(function($item, $key) { return ['pictures.storing.' . $key => [ 'mimes:jpeg,png,jpg', Rule::dimensions()->maxWidth(1000)->maxHeight(500) ]]; })->all(); }
Builds the validation rules for the product pictures. @return array
entailment
protected function createPicturesFor($product, $attr) { $pictures = Images::parse($attr->get('pictures')) ->on($this->basePath. '/' . $product->id) ->store(); $product->pictures()->createMany($pictures); }
Creates pictures for the given product. @param \Antvel\Product\Models\Product $product @param array $attr @return void
entailment
protected function updatePicturesFor($product, $attr) { $current = $product->pictures; $images = Images::parse($pictures = $attr->get('pictures'))->on($this->basePath . '/' . $product->id); //We check whether the request wants deletion, if so //We delete the files and records related to it. if ($images->wantsDeletion()) { $this->deletePictures($product, $images->delete($current)); } //We check whether there was any petition to update pictures, if so, //We retrieve the files related to the given request and proceed //to update the product pictures records. if (isset($pictures['storing']) && count($pictures['storing']) > 0) { //We select the current product pictures that are included in the //request, so we will not delete unrequested pictures. $current = $current->whereIn('id', array_keys($pictures['storing'])); //We delete the files related to the request and return the new info //to be saved for the given product. $pictures = $images->update($current); //if the retrieved pictures were not an array of pictures, //we wrap them in an array to fulfill this requirement. $product->updatePictures( isset($pictures['path']) ? [$pictures] : $pictures ); } if (isset($attr['default_picture'])) { $product->updateDefaultPicture($attr['default_picture']); } }
Updates pictures for the given product. @param \Antvel\Product\Models\Product $product @param array $attr @return void
entailment
public function actionIndex($name) { // First we will check to see if the class already exists. If it does, we don't want // to create the class and overwrite the user's code. So, we will bail out so the // code is untouched. Otherwise, we will continue generating this class' files. if ($this->alreadyExists($name)) { $this->stderr("Notification {$name} already exists!"); return false; } // Make sure the directory exists $dir = CRAFT_BASE_PATH . '/notifications'; if (! is_dir($dir)) { FileHelper::createDirectory($dir); } FileHelper::writeToFile($dir . "/{$name}.php", $this->buildClass($name)); $this->stdout("Notification created successfully."); }
Handle notifications/default console commands The first line of this method docblock is displayed as the description of the Console Command in ./craft help @param string $name @return mixed @throws \yii\base\Exception @throws \yii\base\ErrorException
entailment
protected function all() : array { //TODO: refactor this when working on the front end. $breadcrumb = $this->data->except('page'); if ($this->data->has('category')) { $breadcrumb = $breadcrumb->merge($this->category()); } return $breadcrumb->all(); }
Parses the given data. @return array
entailment
protected function category() : array { $category = explode('|', urldecode($this->data->get('category'))); return [ 'category' => isset($category[0]) ? $category[0] : 1, 'category_name' => isset($category[1]) ? $category[1] : '', ]; }
Returns the category associated with the given data. @return array
entailment
public function index(Request $request, $file) { $options = $request->all(); return Render::image($file, $options)->cast(); }
Renders the given imagen. @param Request $request @param string $file @return void
entailment
public function send( Swift_Mime_SimpleMessage $message, &$failedRecipients = null ) { if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); if ($evt->bubbleCancelled()) { return 0; } } $this->response = $this->_doSend($message, $failedRecipients); $this->_debug("=== Start AWS Response ==="); $this->_debug($this->response->body); $this->_debug("=== End AWS Response ==="); /** @var bool $success */ $success = (200 == $this->response->code); if ($respEvent = $this->_eventDispatcher->createResponseEvent($this, new Swift_Response_AWSResponse( $message, $this->response->xml, $success ), $success)) $this->_eventDispatcher->dispatchEvent($respEvent, 'responseReceived'); if ($evt) { $evt->setResult($success ? Swift_Events_SendEvent::RESULT_SUCCESS : Swift_Events_SendEvent::RESULT_FAILED); $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); } if( $success ) { return count((array) $message->getTo()); } else { return 0; } }
Send the given Message. Recipient/sender data will be retreived from the Message API. The return value is the number of recipients who were accepted for delivery. @param Swift_Mime_SimpleMessage $message @param string[] &$failedRecipients to collect failures by-reference @return int @throws AWSConnectionError
entailment
protected function _doSend( Swift_Mime_SimpleMessage $message, &$failedRecipients = null ) { $date = date( 'D, j F Y H:i:s O' ); if( function_exists( 'hash_hmac' ) and in_array( 'sha1', hash_algos() ) ) { $hmac = base64_encode( hash_hmac( 'sha1', $date, $this->AWSSecretKey, true ) ); } else { $hmac = $this->calculate_RFC2104HMAC( $date, $this->AWSSecretKey ); } $auth = "AWS3-HTTPS AWSAccessKeyId=" . $this->AWSAccessKeyId . ", Algorithm=HmacSHA1, Signature=" . $hmac; $fp = $this->getRawSocket(); $host = parse_url( $this->endpoint, PHP_URL_HOST ); $path = parse_url( $this->endpoint, PHP_URL_PATH ); $socket = new ChunkedTransferSocket( $fp, $host, $path, "POST", $this->persistent ); $socket->header("Date", $date); $socket->header("X-Amzn-Authorization", $auth); $socket->write("Action=SendRawEmail&RawMessage.Data="); $ais = new Swift_AWSInputByteStream($socket); $message->toByteStream($ais); $ais->flushBuffers(); $result = $socket->read(); if( ! $this->persistent ) { fclose($fp); } return $result; }
do send through the API @param Swift_Mime_SimpleMessage $message @param string[] &$failedRecipients to collect failures by-reference @return AWSResponse
entailment
protected function calculate_RFC2104HMAC($data, $key) { return base64_encode ( pack("H*", sha1((str_pad($key, 64, chr(0x00)) ^(str_repeat(chr(0x5c), 64))) . pack("H*", sha1((str_pad($key, 64, chr(0x00)) ^(str_repeat(chr(0x36), 64))) . $data)))) ); }
Cribbed from php-aws - Thanks! https://github.com/tylerhall/php-aws/blob/master/class.awis.php (c) Tyler Hall MIT License
entailment
public function header ( $header, $value ) { if( $this->write_started ) { throw new InvalidOperationException( "Can not write header, body writing has started." ); } fwrite( $this->socket, "$header: $value\r\n" ); fflush( $this->socket ); }
Add an HTTP header @param $header @param $value
entailment
public function write ( $chunk ) { if( $this->write_finished ) { throw new InvalidOperationException( "Can not write, reading has started." ); } if( ! $this->write_started ) { fwrite( $this->socket, "\r\n" ); // Start message body $this->write_started = true; } fwrite( $this->socket, sprintf( "%x\r\n", strlen( $chunk ) ) ); fwrite( $this->socket, $chunk ); fwrite( $this->socket, "\r\n" ); fflush( $this->socket ); }
Write a chunk of data @param $chunk
entailment
public function read () { if( ! $this->write_finished ) { $this->finishWrite(); } $this->read_started = true; $response = new AWSResponse(); while( ! feof( $this->socket ) ) { $line = fgets( $this->socket ); if( AWSResponse::EOF == $response->line( $line ) ) { break; } } $response->complete(); return $response; }
Read the socket for a response
entailment
protected function _setActions($actions) { return (new Collection($actions))->map(function ($value) { $options = (array)$value->get('options') + ['class' => ['btn btn-default']]; $value->set('options', $options); return $value; })->toArray(); }
options property setter @param array $actions Array of options and HTML attributes. @return array
entailment
protected function _get() { $pageTitle = $this->getConfig('scaffold.page_title', __d('CrudView', 'Dashboard')); $this->setConfig('scaffold.page_title', $pageTitle); $this->setConfig('scaffold.autoFields', false); $this->setConfig('scaffold.fields', ['dashboard']); $this->setConfig('scaffold.actions', []); $dashboard = $this->getConfig('scaffold.dashboard', new Dashboard($pageTitle)); $subject = $this->_subject([ 'success' => true, 'dashboard' => $dashboard, ]); $this->_trigger('beforeRender', $subject); $controller = $this->_controller(); $controller->set('dashboard', $subject->dashboard); $controller->set('viewVar', 'dashboard'); $controller->set('title', $subject->dashboard->get('title')); }
HTTP GET handler @return void|\Cake\Http\Response
entailment
public function beforeRenderSidebarNavigation() { $controller = $this->_controller(); $sidebarNavigation = $this->_getSidebarNavigation(); $controller->set('disableSidebar', ($sidebarNavigation === false) ? true : false); $controller->set('sidebarNavigation', $sidebarNavigation); }
beforeRender event @return void
entailment