_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q259000
AmazonSNS.createPlatformEndpoint
test
public function createPlatformEndpoint($platformApplicationArn, $token, $userData = null) { if(empty($platformApplicationArn) || empty($token)) { throw new InvalidArgumentException('Must supply a PlatformApplicationArn & Token to create platform endpoint'); } $attributes = array( 'PlatformApplicationArn' => $platformApplicationArn, 'Token' => $token ); if(!empty($userData)) { $attributes['CustomUserData'] = $userData; } $response = $this->_request('CreatePlatformEndpoint', $attributes); return strval($response->CreatePlatformEndpointResult->EndpointArn); }
php
{ "resource": "" }
q259001
AmazonSNS.publishToEndpoint
test
public function publishToEndpoint($deviceArn, $message) { if (empty($deviceArn) || empty($message)) { throw new InvalidArgumentException('Must supply DeviceArn and Message'); } $resultXml = $this->_request('Publish', array( 'TargetArn' => $deviceArn, 'Message' => $message) ); return strval($resultXml->PublishResult->MessageId); }
php
{ "resource": "" }
q259002
AmazonSNS._request
test
private function _request($action, $params = array()) { // Add in required params $params['Action'] = $action; $params['AWSAccessKeyId'] = $this->access_key; $params['Timestamp'] = gmdate('Y-m-d\TH:i:s.000\Z'); $params['SignatureVersion'] = 2; $params['SignatureMethod'] = 'HmacSHA256'; // Sort and encode into string uksort($params, 'strnatcmp'); $queryString = ''; foreach ($params as $key => $val) { $queryString .= "&{$key}=".rawurlencode($val); } $queryString = substr($queryString, 1); // Form request string $requestString = "GET\n" . $this->endpoint."\n" . "/\n" . $queryString; // Create signature - Version 2 $params['Signature'] = base64_encode( hash_hmac('sha256', $requestString, $this->secret_key, true) ); // Finally create request $request = $this->endpoint . '/?' . http_build_query($params, '', '&'); // Instantiate cUrl and perform request $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $request); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); $info = curl_getinfo($ch); // Close cUrl curl_close($ch); // Load XML response $xmlResponse = simplexml_load_string($output); // Check return code if($this->_checkGoodResponse($info['http_code']) === false) { // Response not in 200 range if(isset($xmlResponse->Error)) { // Amazon returned an XML error throw new SNSException(strval($xmlResponse->Error->Code) . ': ' . strval($xmlResponse->Error->Message), $info['http_code']); } else { // Some other problem throw new APIException('There was a problem executing this request', $info['http_code']); } } else { // All good return $xmlResponse; } }
php
{ "resource": "" }
q259003
AmazonSNS._processXmlToArray
test
private function _processXmlToArray(SimpleXMLElement $xmlArray) { $returnArray = array(); // Process into array foreach($xmlArray as $xmlElement) { $elementArray = array(); // Loop through each element foreach($xmlElement as $key => $element) { // Use strval() to make sure no SimpleXMLElement objects remain $elementArray[$key] = strval($element); } // Store array of elements $returnArray[] = $elementArray; } return $returnArray; }
php
{ "resource": "" }
q259004
Queue.clear
test
public function clear() { if ($this->getPersistor()->clear()) { $event = new Event($this); $this->getEventDispatcher()->dispatch(self::EVENT_CLEAR_ALL_TASKS, $event); return true; } return false; }
php
{ "resource": "" }
q259005
Beanstalk._convertPriority
test
protected function _convertPriority($priority) { if (!is_numeric($priority)) { throw new \Exeption('Error while converting priority, agrument is ' . 'not a number, '. gettype($priority) .' sent'); } switch ($priority) { case Task::PRIORITY_LOW: // Least urgent Beanstalkd priority return 4294967295; case Task::PRIORITY_NORMAL: return PheanstalkInterface::DEFAULT_PRIORITY; case Task::PRIORITY_HIGH: return 1024; default: return 512; } }
php
{ "resource": "" }
q259006
Worker.run
test
public function run() { // Start timing $this->_startTime(); // Get next task with set priority (or any task if priority not set) if (null === ($task = $this->getQueue()->getTask($this->getPriority()))) { $this->_sleep(); return; } $event = new Event($this); $event->setArgument('startTime', $this->_startTime); $event->setTask($task); $this->getQueue()->getEventDispatcher()->dispatch(self::EVENT_START_PROCESSING_TASK, $event); $this->_runTask($task); $event = new Event($this); $event->setArgument('elapsedTime', $this->_getPassedTime()); $event->setTask($task); $this->getQueue()->getEventDispatcher()->dispatch(self::EVENT_END_PROCESSING_TASK, $event); // After working, sleep $this->_sleep(); return $task; }
php
{ "resource": "" }
q259007
SparkServiceProvider.customizeSettingsTabs
test
protected function customizeSettingsTabs() { Spark::settingsTabs()->configure(function ($tabs) { return [ $tabs->profile(), $tabs->teams(), $tabs->security(), $tabs->subscription(), // $tabs->make('Name', 'view', 'fa-icon'), ]; }); Spark::teamSettingsTabs()->configure(function ($tabs) { return [ $tabs->owner(), $tabs->membership(), // $tabs->make('Name', 'view', 'fa-icon'), ]; }); }
php
{ "resource": "" }
q259008
InvitationController.getInvitation
test
public function getInvitation($code) { $model = config('auth.model'); $model = get_class((new $model)->invitations() ->getQuery()->getModel()); $invitation = (new $model)->with('team.owner') ->where('token', $code)->firstOrFail(); if ($invitation->isExpired()) { $invitation->delete(); abort(404); } $invitation->team->setVisible(['name', 'owner']); $invitation->team->owner->setVisible(['name']); return $invitation; }
php
{ "resource": "" }
q259009
Spark.createDefaultSettingsTabs
test
protected static function createDefaultSettingsTabs() { $tabs = [(new DashboardTabs)->profile(), (new DashboardTabs)->security()]; if (count(static::plans()->active()) > 0) { $tabs[] = (new DashboardTabs)->subscription(); } return new DashboardTabs($tabs); }
php
{ "resource": "" }
q259010
Coupon.fromStripeCoupon
test
public static function fromStripeCoupon($stripeCoupon) { $coupon = new static($stripeCoupon->id); if ($stripeCoupon->duration === 'forever') { $coupon->shouldLastForever(); } elseif ($stripeCoupon->duration === 'once') { $coupon->shouldLastOnce(); } else { $coupon->months($stripeCoupon->duration_in_months); } if (! is_null($stripeCoupon->amount_off)) { $coupon->amountOff($stripeCoupon->amount_off / 100); } else { $coupon->percentOff($stripeCoupon->percent_off); } return $coupon; }
php
{ "resource": "" }
q259011
SubscriptionController.getCoupon
test
public function getCoupon($code) { Stripe::setApiKey(config('services.stripe.secret')); if (count(Spark::plans()) === 0) { abort(404); } try { return response()->json( Coupon::fromStripeCoupon(StripeCoupon::retrieve($code)) ); } catch (Exception $e) { abort(404); } }
php
{ "resource": "" }
q259012
SubscriptionController.getCouponForUser
test
public function getCouponForUser() { Stripe::setApiKey(config('services.stripe.secret')); if (count(Spark::plans()) === 0) { abort(404); } try { $customer = StripeCustomer::retrieve(Auth::user()->stripe_id); if ($customer->discount) { return response()->json( Coupon::fromStripeCoupon( StripeCoupon::retrieve($customer->discount->coupon->id) ) ); } else { abort(404); } } catch (Exception $e) { abort(404); } }
php
{ "resource": "" }
q259013
TeamController.getTeam
test
public function getTeam(Request $request, $teamId) { return $this->teams->getTeam($request->user(), $teamId); }
php
{ "resource": "" }
q259014
TeamController.getTeamRoles
test
public function getTeamRoles() { $roles = []; foreach (Spark::roles() as $key => $value) { $roles[] = ['value' => $key, 'text' => $value]; } return response()->json($roles); }
php
{ "resource": "" }
q259015
ProfileController.updateUserProfile
test
public function updateUserProfile(Request $request) { $this->validateUserProfile($request); $originalEmail = Auth::user()->email; if (Spark::$updateProfilesWith) { $this->callCustomUpdater(Spark::$updateProfilesWith, $request); } else { Auth::user()->fill($request->all())->save(); } if (Auth::user()->stripe_id && $originalEmail !== Auth::user()->email) { $this->updateStripeEmailAddress(); } event(new ProfileUpdated(Auth::user())); return $this->users->getCurrentUser(); }
php
{ "resource": "" }
q259016
ProfileController.validateUserProfile
test
protected function validateUserProfile(Request $request) { if (Spark::$validateProfileUpdatesWith) { $this->callCustomValidator( Spark::$validateProfileUpdatesWith, $request ); } else { $this->validate($request, [ 'name' => 'required|max:255', 'email' => 'required|email|unique:users,email,'.Auth::id() ]); } }
php
{ "resource": "" }
q259017
ProfileController.updateStripeEmailAddress
test
protected function updateStripeEmailAddress() { $customer = Auth::user()->subscription()->getStripeCustomer(); $customer->email = Auth::user()->email; $customer->save(); }
php
{ "resource": "" }
q259018
Install.installJavaScript
test
protected function installJavaScript() { if (! is_dir('resources/assets/js')) { mkdir(base_path('resources/assets/js')); } if (! is_dir('resources/assets/js/spark')) { mkdir(base_path('resources/assets/js/spark')); } copy( SPARK_PATH.'/resources/stubs/resources/assets/js/app.js', base_path('resources/assets/js/app.js') ); copy( SPARK_PATH.'/resources/stubs/resources/assets/js/spark/components.js', base_path('resources/assets/js/spark/components.js') ); }
php
{ "resource": "" }
q259019
Install.installEnvironmentVariables
test
protected function installEnvironmentVariables() { $env = file_get_contents(base_path('.env')); if (str_contains($env, 'AUTHY_KEY=')) { return; } (new Filesystem)->append( base_path('.env'), PHP_EOL.'AUTHY_KEY='.PHP_EOL.PHP_EOL. 'STRIPE_KEY='.PHP_EOL. 'STRIPE_SECRET='.PHP_EOL ); }
php
{ "resource": "" }
q259020
SubscriptionController.subscribe
test
public function subscribe(Request $request) { $this->validate($request, [ 'plan' => 'required', 'terms' => 'required|accepted', 'stripe_token' => 'required', ]); $plan = Spark::plans()->find($request->plan); $stripeCustomer = Auth::user()->stripe_id ? Auth::user()->subscription()->getStripeCustomer() : null; Auth::user()->subscription($request->plan) ->skipTrial() ->create($request->stripe_token, [ 'email' => Auth::user()->email ], $stripeCustomer); event(new Subscribed(Auth::user())); return $this->users->getCurrentUser(); }
php
{ "resource": "" }
q259021
SubscriptionController.changeSubscriptionPlan
test
public function changeSubscriptionPlan(Request $request) { $this->validate($request, [ 'plan' => 'required', ]); $plan = Spark::plans()->find($request->plan); if ($plan->price() === 0) { $this->cancelSubscription(); } else { Auth::user()->subscription($request->plan) ->maintainTrial()->prorate()->swapAndInvoice(); } event(new SubscriptionPlanChanged(Auth::user())); return $this->users->getCurrentUser(); }
php
{ "resource": "" }
q259022
SubscriptionController.updateCard
test
public function updateCard(Request $request) { $this->validate($request, [ 'stripe_token' => 'required' ]); Auth::user()->updateCard($request->stripe_token); return $this->users->getCurrentUser(); }
php
{ "resource": "" }
q259023
SubscriptionController.updateExtraBillingInfo
test
public function updateExtraBillingInfo(Request $request) { Auth::user()->extra_billing_info = $request->text; Auth::user()->save(); }
php
{ "resource": "" }
q259024
SubscriptionController.cancelSubscription
test
public function cancelSubscription() { Auth::user()->subscription()->cancelAtEndOfPeriod(); event(new SubscriptionCancelled(Auth::user())); return $this->users->getCurrentUser(); }
php
{ "resource": "" }
q259025
SubscriptionController.resumeSubscription
test
public function resumeSubscription() { $user = Auth::user(); $user->subscription($user->stripe_plan)->skipTrial()->resume(); event(new SubscriptionResumed(Auth::user())); return $this->users->getCurrentUser(); }
php
{ "resource": "" }
q259026
SubscriptionController.downloadInvoice
test
public function downloadInvoice(Request $request, $invoiceId) { $data = array_merge([ 'vendor' => 'Vendor', 'product' => 'Product', 'vat' => new ViewExpression(nl2br(e($request->user()->extra_billing_info))), ], Spark::generateInvoicesWith()); return Auth::user()->downloadInvoice($invoiceId, $data); }
php
{ "resource": "" }
q259027
Plan.price
test
public function price($price = null) { if (is_null($price)) { return $this->price; } $this->price = $price; return $this; }
php
{ "resource": "" }
q259028
Plan.currencySymbol
test
public function currencySymbol($currencySymbol) { if (is_null($currencySymbol)) { return $this->currencySymbol; } $this->currencySymbol = $currencySymbol; return $this; }
php
{ "resource": "" }
q259029
Plan.trialDays
test
public function trialDays($trialDays = null) { if (is_null($trialDays)) { return $this->trialDays; } $this->trialDays = $trialDays; return $this; }
php
{ "resource": "" }
q259030
Plan.tier
test
public function tier($tier = null) { if (is_null($tier)) { return $this->tier; } $this->tier = $tier; return $this; }
php
{ "resource": "" }
q259031
Plan.features
test
public function features(array $features = null) { if (is_null($features)) { return $this->features; } $this->features = $features; return $this; }
php
{ "resource": "" }
q259032
UserRepository.getCurrentUser
test
public function getCurrentUser() { $user = Spark::user(); if (Spark::usingTeams()) { $user->currentTeam; } return $user->withHidden(['last_four', 'extra_billing_info']); }
php
{ "resource": "" }
q259033
UserRepository.createUserFromRegistrationRequest
test
public function createUserFromRegistrationRequest(Request $request, $withSubscription = false) { return DB::transaction(function () use ($request, $withSubscription) { $user = $this->createNewUser($request, $withSubscription); if ($withSubscription) { $this->createSubscriptionOnStripe($request, $user); } return $user; }); }
php
{ "resource": "" }
q259034
UserRepository.createNewUser
test
protected function createNewUser(Request $request, $withSubscription) { if (Spark::$createUsersWith) { return $this->callCustomUpdater(Spark::$createUsersWith, $request, [$withSubscription]); } else { return $this->createDefaultUser($request); } }
php
{ "resource": "" }
q259035
UserRepository.createDefaultUser
test
protected function createDefaultUser(Request $request) { $model = config('auth.model'); return (new $model)->create([ 'name' => $request->name, 'email' => $request->email, 'password' => bcrypt($request->password), ]); }
php
{ "resource": "" }
q259036
UserRepository.createSubscriptionOnStripe
test
protected function createSubscriptionOnStripe(Request $request, $user) { $plan = Spark::plans()->find($request->plan); $subscription = $user->subscription($plan->id); if ($plan->hasTrial()) { $subscription->trialFor(Carbon::now()->addDays($plan->trialDays)); } if ($request->coupon) { $subscription->withCoupon($request->coupon); } $subscription->create($request->stripe_token, [ 'email' => $user->email, ]); }
php
{ "resource": "" }
q259037
Authy.register
test
public function register(TwoFactorAuthenticatable $user) { $key = env('AUTHY_KEY'); $response = json_decode((new HttpClient)->post('https://api.authy.com/protected/json/users/new?api_key='.$key, [ 'form_params' => [ 'user' => [ 'email' => $user->getEmailForTwoFactorAuth(), 'cellphone' => str_replace(['-', '.'], '', $user->getAuthPhoneNumber()), 'country_code' => $user->getAuthCountryCode(), ], ], ])->getBody(), true); $user->setTwoFactorAuthProviderOptions([ 'id' => $response['user']['id'] ]); }
php
{ "resource": "" }
q259038
Authy.tokenIsValid
test
public function tokenIsValid(TwoFactorAuthenticatable $user, $token) { try { $key = env('AUTHY_KEY'); $options = $user->getTwoFactorAuthProviderOptions(); $response = json_decode((new HttpClient)->get( 'https://api.authy.com/protected/json/verify/'.$token.'/'.$options['id'].'?force=true&api_key='.$key )->getBody(), true); return $response['token'] === 'is valid'; } catch (Exception $e) { return false; } }
php
{ "resource": "" }
q259039
Authy.delete
test
public function delete(TwoFactorAuthenticatable $user) { $key = env('AUTHY_KEY'); $options = $user->getTwoFactorAuthProviderOptions(); (new HttpClient)->post( 'https://api.authy.com/protected/json/users/delete/'.$options['id'].'?api_key='.$key ); $user->setTwoFactorAuthProviderOptions([]); }
php
{ "resource": "" }
q259040
DashboardController.show
test
public function show(Request $request) { $data = [ 'activeTab' => $request->get('tab', Spark::firstSettingsTabKey()), 'invoices' => [], 'user' => $this->users->getCurrentUser(), ]; if (Auth::user()->stripe_id) { $data['invoices'] = Cache::remember('spark:invoices:'.Auth::id(), 30, function () { return Auth::user()->invoices(); }); } return view('spark::settings.dashboard', $data); }
php
{ "resource": "" }
q259041
Team.inviteUserByEmail
test
public function inviteUserByEmail($email) { $model = config('auth.model'); $invitedUser = (new $model)->where('email', $email)->first(); $invitation = $this->invitations() ->where('email', $email)->first(); if (! $invitation) { $invitation = $this->invitations()->create([ 'user_id' => $invitedUser ? $invitedUser->id : null, 'email' => $email, 'token' => str_random(40), ]); } $email = $invitation->user_id ? 'spark::emails.team.invitations.existing' : 'spark::emails.team.invitations.new'; Mail::send($email, compact('invitation'), function ($m) use ($invitation) { $m->to($invitation->email)->subject('New Invitation!'); }); return $invitation; }
php
{ "resource": "" }
q259042
Team.removeUserById
test
public function removeUserById($userId) { $this->users()->detach([$userId]); $userModel = config('auth.model'); $removedUser = (new $userModel)->find($userId); if ($removedUser) { $removedUser->refreshCurrentTeam(); } }
php
{ "resource": "" }
q259043
InvitationController.sendTeamInvitation
test
public function sendTeamInvitation(Request $request, $teamId) { $user = $request->user(); $this->validate($request, [ 'email' => 'required|max:255|email', ]); $team = $user->teams() ->where('owner_id', $user->id) ->findOrFail($teamId); if ($team->invitations()->where('email', $request->email)->exists()) { return response()->json(['email' => 'That user is already invited to the team.'], 422); } $team->inviteUserByEmail($request->email); return $team->fresh(['users', 'invitations']); }
php
{ "resource": "" }
q259044
InvitationController.acceptTeamInvitation
test
public function acceptTeamInvitation(Request $request, $inviteId) { $user = $request->user(); $invitation = $user->invitations()->findOrFail($inviteId); $user->joinTeamById($invitation->team_id); $invitation->delete(); return $this->teams->getAllTeamsForUser($user); }
php
{ "resource": "" }
q259045
Tabs.make
test
public function make($name, $view, $icon, callable $displayable = null) { return new Tab($name, $view, $icon, $displayable); }
php
{ "resource": "" }
q259046
Tabs.displayable
test
public function displayable() { $arguments = func_get_args(); return array_values(array_filter($this->tabs, function ($tab) use ($arguments) { return call_user_func_array([$tab, 'displayable'], $arguments); })); }
php
{ "resource": "" }
q259047
SparkServiceProvider.defineResources
test
protected function defineResources() { $this->loadViewsFrom(SPARK_PATH.'/resources/views', 'spark'); if ($this->app->runningInConsole()) { $this->publishes([ SPARK_PATH.'/resources/views' => base_path('resources/views/vendor/spark'), ], 'spark-full'); $this->publishes([ SPARK_PATH.'/resources/views/emails' => base_path('resources/views/vendor/spark/emails'), SPARK_PATH.'/resources/views/welcome.blade.php' => base_path('resources/views/vendor/spark/welcome.blade.php'), SPARK_PATH.'/resources/views/nav/guest.blade.php' => base_path('resources/views/vendor/spark/nav/guest.blade.php'), SPARK_PATH.'/resources/views/layouts/app.blade.php' => base_path('resources/views/vendor/spark/layouts/app.blade.php'), SPARK_PATH.'/resources/views/common/footer.blade.php' => base_path('resources/views/vendor/spark/common/footer.blade.php'), SPARK_PATH.'/resources/views/nav/authenticated.blade.php' => base_path('resources/views/vendor/spark/nav/authenticated.blade.php'), SPARK_PATH.'/resources/views/layouts/common/head.blade.php' => base_path('resources/views/vendor/spark/layouts/common/head.blade.php'), SPARK_PATH.'/resources/views/settings/tabs/profile.blade.php' => base_path('resources/views/vendor/spark/settings/tabs/profile.blade.php'), SPARK_PATH.'/resources/views/settings/tabs/security.blade.php' => base_path('resources/views/vendor/spark/settings/tabs/security.blade.php'), SPARK_PATH.'/resources/views/settings/team/tabs/owner.blade.php' => base_path('resources/views/vendor/spark/settings/team/tabs/owner.blade.php'), SPARK_PATH.'/resources/views/auth/registration/simple/basics.blade.php' => base_path('resources/views/vendor/spark/auth/registration/simple/basics.blade.php'), SPARK_PATH.'/resources/views/auth/registration/subscription/basics.blade.php' => base_path('resources/views/vendor/spark/auth/registration/subscription/basics.blade.php'), SPARK_PATH.'/resources/views/settings/team/tabs/membership/modals/edit-team-member.blade.php' => base_path('resources/views/vendor/spark/settings/team/tabs/membership/modals/edit-team-member.blade.php'), ], 'spark-basics'); } }
php
{ "resource": "" }
q259048
SparkServiceProvider.defineServices
test
protected function defineServices() { $services = [ RegistrarContract::class => Registrar::class, InvoiceNotifier::class => EmailInvoiceNotifier::class, UserRepositoryContract::class => UserRepository::class, TeamRepositoryContract::class => TeamRepository::class, ]; foreach ($services as $key => $value) { $this->app->bindIf($key, $value); } }
php
{ "resource": "" }
q259049
EmailInvoiceNotifier.notify
test
public function notify(Authenticatable $user, Invoice $invoice) { $invoiceData = array_merge([ 'vendor' => 'Vendor', 'product' => 'Product', 'vat' => new ViewExpression(nl2br(e($user->extra_billing_info))), ], Spark::generateInvoicesWith()); $data = compact('user', 'invoice', 'invoiceData'); Mail::send('spark::emails.billing.invoice', $data, function ($message) use ($user, $invoice, $invoiceData) { $message->to($user->email, $user->name) ->subject('Your '.$invoiceData['product'].' Invoice') ->attachData($invoice->pdf($invoiceData), 'invoice.pdf'); }); }
php
{ "resource": "" }
q259050
WebhookController.handleInvoicePaymentSucceeded
test
protected function handleInvoicePaymentSucceeded(array $payload) { $model = config('auth.model'); $user = (new $model)->where( 'stripe_id', $payload['data']['object']['customer'] )->first(); if (is_null($user)) { return; } app(InvoiceNotifier::class)->notify( $user, $user->findInvoice($payload['data']['object']['id']) ); }
php
{ "resource": "" }
q259051
TeamRepository.create
test
public function create($user, array $data) { $team = $user->teams()->create( ['name' => $data['name']], ['role' => 'owner'] ); $team->owner_id = $user->id; $team->save(); return $team; }
php
{ "resource": "" }
q259052
TeamRepository.getAllTeamsForUser
test
public function getAllTeamsForUser($user) { $teams = $user->teams()->with('owner')->get(); foreach ($teams as $team) { $team->owner->setVisible(['name']); } return $teams; }
php
{ "resource": "" }
q259053
TeamRepository.getPendingInvitationsForUser
test
public function getPendingInvitationsForUser($user) { $invitations = $user->invitations()->with('team.owner')->get(); foreach ($invitations as $invite) { $invite->setVisible(['id', 'team']); $invite->team->setVisible(['name', 'owner']); $invite->team->owner->setVisible(['name']); } return $invitations; }
php
{ "resource": "" }
q259054
TeamRepository.attachUserToTeamByInvitation
test
public function attachUserToTeamByInvitation($invitationId, $user) { $userModel = get_class($user); $inviteModel = get_class((new $userModel)->invitations()->getQuery()->getModel()); $invitation = (new $inviteModel)->where('token', $invitationId)->first(); if ($invitation) { $invitation->team->users()->attach([$user->id], ['role' => Spark::defaultRole()]); $user->switchToTeam($invitation->team); $invitation->delete(); } }
php
{ "resource": "" }
q259055
Plans.find
test
public function find($id) { foreach ($this->plans as $plan) { if ($plan->id === $id) { return $plan; } } throw new Exception("Unable to find plan with ID [{$id}]."); }
php
{ "resource": "" }
q259056
Plans.tier
test
public function tier($tier) { return new Plans(array_values(array_filter($this->plans, function ($plan) use ($tier) { return $plan->tier === $tier; }))); }
php
{ "resource": "" }
q259057
CanJoinTeams.currentTeam
test
public function currentTeam() { if (is_null($this->current_team_id) && $this->hasTeams()) { $this->switchToTeam($this->teams->first()); return $this->currentTeam(); } elseif (! is_null($this->current_team_id)) { $currentTeam = $this->teams->find($this->current_team_id); return $currentTeam ?: $this->refreshCurrentTeam(); } }
php
{ "resource": "" }
q259058
CanJoinTeams.ownsTeam
test
public function ownsTeam($team) { if (is_null($team->owner_id) || is_null($this->id)) { return false; } return $this->id === $team->owner_id; }
php
{ "resource": "" }
q259059
CanJoinTeams.teamRole
test
public function teamRole($team) { $team = $this->teams->find($team->id); if ($team) { return $team->pivot->role; } }
php
{ "resource": "" }
q259060
TeamController.store
test
public function store(Request $request) { $user = $request->user(); if (Spark::$validateNewTeamsWith) { $this->callCustomValidator( Spark::$validateNewTeamsWith, $request ); } else { $this->validate($request, [ 'name' => 'required|max:255', ]); } $team = $this->teams->create( $user, ['name' => $request->name] ); return $this->teams->getAllTeamsForUser($user); }
php
{ "resource": "" }
q259061
TeamController.edit
test
public function edit(Request $request, $teamId) { $user = $request->user(); $team = $user->teams()->findOrFail($teamId); $activeTab = $request->get( 'tab', Spark::firstTeamSettingsTabKey($team, $user) ); return view('spark::settings.team', compact('team', 'activeTab')); }
php
{ "resource": "" }
q259062
TeamController.update
test
public function update(Request $request, $teamId) { $user = $request->user(); $team = $user->teams() ->where('owner_id', $user->id) ->findOrFail($teamId); $this->validateTeamUpdate($request, $team); if (Spark::$updateTeamsWith) { $this->callCustomUpdater(Spark::$updateTeamsWith, $request, [$team]); } else { $team->fill(['name' => $request->name])->save(); } return $this->teams->getTeam($user, $teamId); }
php
{ "resource": "" }
q259063
TeamController.switchCurrentTeam
test
public function switchCurrentTeam(Request $request, $teamId) { $user = $request->user(); $team = $user->teams()->findOrFail($teamId); $user->switchToTeam($team); return back(); }
php
{ "resource": "" }
q259064
TeamController.updateTeamMember
test
public function updateTeamMember(Request $request, $teamId, $userId) { $user = $request->user(); $team = $user->teams() ->where('owner_id', $user->id)->findOrFail($teamId); $userToUpdate = $team->users->find($userId); if (! $userToUpdate) { abort(404); } $this->validateTeamMemberUpdate($request, $team, $userToUpdate); if (Spark::$updateTeamMembersWith) { $this->callCustomUpdater(Spark::$updateTeamMembersWith, $request, [$team, $userToUpdate]); } else { $userToUpdate->teams()->updateExistingPivot( $team->id, ['role' => $request->role] ); } return $this->teams->getTeam($user, $teamId); }
php
{ "resource": "" }
q259065
TeamController.removeTeamMember
test
public function removeTeamMember(Request $request, $teamId, $userId) { $user = $request->user(); $team = $user->teams() ->where('owner_id', $user->id)->findOrFail($teamId); $team->removeUserById($userId); return $this->teams->getTeam($user, $teamId); }
php
{ "resource": "" }
q259066
TeamController.leaveTeam
test
public function leaveTeam(Request $request, $teamId) { $user = $request->user(); $team = $user->teams() ->where('owner_id', '!=', $user->id) ->where('id', $teamId)->firstOrFail(); $team->removeUserById($user->id); return $this->teams->getAllTeamsForUser($user); }
php
{ "resource": "" }
q259067
TeamController.destroy
test
public function destroy(Request $request, $teamId) { $user = $request->user(); $team = $request->user()->teams() ->where('owner_id', $user->id) ->findOrFail($teamId); event(new DeletingTeam($team)); $team->users()->where('current_team_id', $team->id) ->update(['current_team_id' => null]); $team->users()->detach(); $team->delete(); return $this->teams->getAllTeamsForUser($user); }
php
{ "resource": "" }
q259068
InteractsWithSparkHooks.callCustomValidator
test
public function callCustomValidator($callback, Request $request, array $arguments = []) { if (is_string($callback)) { list($class, $method) = explode('@', $callback); $callback = [app($class), $method]; } $validator = call_user_func($callback, array_merge([$request], $arguments)); $validator = $validator instanceof ValidatorContract ? $validator : Validator::make($request->all(), $validator); if ($validator->fails()) { $this->throwValidationException($request, $validator); } }
php
{ "resource": "" }
q259069
InteractsWithSparkHooks.callCustomUpdater
test
public function callCustomUpdater($callback, Request $request, array $arguments = []) { if (is_string($callback)) { list($class, $method) = explode('@', $callback); $callback = [app($class), $method]; } return call_user_func_array($callback, array_merge([$request], $arguments)); }
php
{ "resource": "" }
q259070
SecurityController.updatePassword
test
public function updatePassword(Request $request) { $this->validate($request, [ 'old_password' => 'required', 'password' => 'required|confirmed|max:6', ]); if (! Hash::check($request->old_password, Auth::user()->password)) { return response()->json( ['The old password you provided is incorrect.'], 422 ); } Auth::user()->password = Hash::make($request->password); Auth::user()->save(); }
php
{ "resource": "" }
q259071
SecurityController.enableTwoFactorAuth
test
public function enableTwoFactorAuth(Request $request) { if (! is_null($response = $this->validateEnablingTwoFactorAuth($request))) { return $response; } $user = Auth::user(); $user->setAuthPhoneInformation( $request->country_code, $request->phone_number ); try { Spark::twoFactorProvider()->register($user); } catch (Exception $e) { app(ExceptionHandler::class)->report($e); return response()->json(['The provided phone information is invalid.'], 422); } $user->save(); return $this->users->getCurrentUser(); }
php
{ "resource": "" }
q259072
SecurityController.validateEnablingTwoFactorAuth
test
protected function validateEnablingTwoFactorAuth(Request $request) { $input = $request->all(); if (isset($input['phone_number'])) { $input['phone_number'] = str_replace(['-', '.'], '', $input['phone_number']); } $validator = Validator::make($input, [ 'country_code' => 'required|numeric|integer', 'phone_number' => 'required|numeric', ]); if ($validator->fails()) { return response()->json($validator->errors()->all(), 422); } }
php
{ "resource": "" }
q259073
SecurityController.disableTwoFactorAuth
test
public function disableTwoFactorAuth(Request $request) { Spark::twoFactorProvider()->delete(Auth::user()); Auth::user()->save(); return $this->users->getCurrentUser(); }
php
{ "resource": "" }
q259074
AuthController.authenticated
test
protected function authenticated(Request $request, Authenticatable $user) { if (Spark::supportsTwoFactorAuth() && Spark::twoFactorProvider()->isEnabled($user)) { return $this->logoutAndRedirectToTokenScreen($request, $user); } return redirect()->intended($this->redirectPath()); }
php
{ "resource": "" }
q259075
AuthController.logoutAndRedirectToTokenScreen
test
protected function logoutAndRedirectToTokenScreen(Request $request, Authenticatable $user) { Auth::logout(); $request->session()->put('spark:auth:id', $user->id); return redirect('login/token'); }
php
{ "resource": "" }
q259076
AuthController.postToken
test
public function postToken(Request $request) { $this->validate($request, ['token' => 'required']); if (! session('spark:auth:id')) { return redirect('login'); } $model = config('auth.model'); $user = (new $model)->findOrFail( $request->session()->pull('spark:auth:id') ); if (Spark::twoFactorProvider()->tokenIsValid($user, $request->token)) { Auth::login($user); return redirect()->intended($this->redirectPath()); } else { return back(); } }
php
{ "resource": "" }
q259077
AuthController.getRegister
test
public function getRegister(Request $request) { if (Spark::forcingPromotion() && ! $request->query('coupon')) { if (count($request->query()) > 0) { return redirect($request->fullUrl().'&coupon='.Spark::forcedPromotion()); } else { return redirect($request->fullUrl().'?coupon='.Spark::forcedPromotion()); } } if (count($this->plans->paid()) > 0) { return view('spark::auth.registration.subscription'); } else { return view('spark::auth.registration.simple'); } }
php
{ "resource": "" }
q259078
AuthController.validateRegistration
test
protected function validateRegistration(Request $request, $withSubscription = false) { if (Spark::$validateProfileUpdatesWith) { $this->callCustomValidator( Spark::$validateProfileUpdatesWith, $request, [$withSubscription] ); } else { $this->validateDefaultRegistration($request, $withSubscription); } }
php
{ "resource": "" }
q259079
AuthController.validateDefaultRegistration
test
protected function validateDefaultRegistration(Request $request, $withSubscription) { $validator = Validator::make($request->all(), [ 'name' => 'required|max:255', 'email' => 'required|email|unique:users', 'password' => 'required|confirmed|min:6', 'terms' => 'required|accepted', ]); if ($withSubscription) { $validator->mergeRules('stripe_token', 'required'); if ($request->coupon) { $validator->after(function ($validator) use ($request) { $this->validateCoupon($validator, $request); }); } } if ($validator->fails()) { $this->throwValidationException($request, $validator); } }
php
{ "resource": "" }
q259080
AuthController.validateCoupon
test
protected function validateCoupon($validator, Request $request) { try { $coupon = StripeCoupon::retrieve( $request->coupon, ['api_key' => config('services.stripe.secret')] ); if ($coupon && $coupon->valid) { return; } } catch (Exception $e) { // } $validator->errors()->add('coupon', 'The provided coupon code is invalid.'); }
php
{ "resource": "" }
q259081
AuthController.getLogout
test
public function getLogout(Request $request) { $request->session()->flush(); Auth::logout(); return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/'); }
php
{ "resource": "" }
q259082
BasePresenter.flashMessage
test
public function flashMessage($message, $type = 'info') { return parent::flashMessage($this->translator->translate($message), $type); }
php
{ "resource": "" }
q259083
CreateEventCapableTrait._createEvent
test
protected function _createEvent($name, $params = [], $target = null, $propagation = true) { return new Event($name, $params, $target, $propagation); }
php
{ "resource": "" }
q259084
ExceptionHandler.registerException
test
function registerException(string $class, callable $exporter, callable $importer) { if(!\class_exists($class, true)) { throw new \InvalidArgumentException('Given class does not exist'); } elseif(!\in_array(\Throwable::class, \class_implements($class))) { throw new \InvalidArgumentException('Given class is not a Throwable'); } elseif($exporter instanceof \Closure || $importer instanceof \Closure) { throw new \LogicException('Closures are not supported'); } $this->exceptions[$class] = array( 'export' => $exporter, 'import' => $importer ); return $this; }
php
{ "resource": "" }
q259085
ExceptionHandler.exportException
test
function exportException(\Throwable $error) { $class = \get_class($error); if(!isset($this->exceptions[$class])) { throw new \BadMethodCallException('Given exception "'.$class.'" is not registered'); } $export = ((array) $this->exceptions[$class]['export'])($error); $export['class'] = $class; $export['phoebeExceptionHandler'] = true; return $export; }
php
{ "resource": "" }
q259086
ExceptionHandler.importException
test
function importException(array $error) { $class = $error['class'] ?? null; if(!isset($this->exceptions[$class])) { throw new \BadMethodCallException('Given exception "'.$class.'" is not registered'); } return ((array) $this->exceptions[$class]['import'])($error); }
php
{ "resource": "" }
q259087
NormalizeEventCapableTrait._normalizeEvent
test
protected function _normalizeEvent($event, $params = [], $target = null) { if (is_string($event) || $event instanceof Stringable) { return $this->_createEvent($this->_normalizeString($event), $params, $target); } if (!($event instanceof EventInterface)) { throw $this->_createInvalidArgumentException( $this->__('Argument is not a string, stringable object or event instance'), null, null, $event ); } if ($target !== null) { $event->setTarget($target); } if (count($params) > 0) { $event->setParams($params + $event->getParams()); } return $event; }
php
{ "resource": "" }
q259088
WpHandlerWrapperCacheTrait._getWpHandlerWrapper
test
protected function _getWpHandlerWrapper($name, $callback) { $cbHash = $this->_hashWpHandler($name, $callback); // Create if not exists if (!isset($this->handlerWrappers[$cbHash])) { $this->handlerWrappers[$cbHash] = $this->_createWpHandlerWrapper( $name, $callback, $this->_getThrowOnPropStop() ); } return $this->handlerWrappers[$cbHash]; }
php
{ "resource": "" }
q259089
EventCacheTrait._createCachedEvent
test
protected function _createCachedEvent($event, array $args = []) { $event = $this->_normalizeEvent($event, $args); $name = $event->getName(); return $this->eventCache[$name] = $event; }
php
{ "resource": "" }
q259090
EventCacheTrait._hasCachedEvent
test
protected function _hasCachedEvent($event) { $name = ($event instanceof EventInterface) ? $event->getName() : $event; return isset($this->eventCache[$name]); }
php
{ "resource": "" }
q259091
EventCacheTrait._getCachedEvent
test
protected function _getCachedEvent($event, array $args = []) { $name = ($event instanceof EventInterface) ? $event->getName() : $event; // Create event instance if it does not exist if (!$this->_hasCachedEvent($name)) { $this->_createCachedEvent($event, $args); } return $this->eventCache[$name]; }
php
{ "resource": "" }
q259092
EventCacheTrait._removeCachedEvent
test
protected function _removeCachedEvent($event) { $name = ($event instanceof EventInterface) ? $event->getName() : $event; unset($this->eventCache[$name]); return $this; }
php
{ "resource": "" }
q259093
CreateWpHandlerWrapperCapableTrait._createWpHandlerWrapper
test
protected function _createWpHandlerWrapper($name, $callback, $throwOnPropStop = false) { $eventCache = $this; /* * $name - The name of the event * $callback - The actual handler callback * $eventCache - The callback for retrieving events from cache * $throwOnPropStop - If true, an exception is thrown when propagation is stopped. */ return function () use ($name, &$callback, $eventCache, $throwOnPropStop) { $fnArgs = func_get_args(); // Detect whether the first argument given to the handler is an EventInterface $firstArg = count($fnArgs) === 1 ? $fnArgs[0] : null; if ($firstArg instanceof EventInterface) { // If first argument is an event instance, put in cache $event = $eventCache->_getCachedEvent($firstArg); } else { // Creates and retrieves an instance if an event name $event = $eventCache->_getCachedEvent($name, $fnArgs); } // Call original handler if propagation is not stopped if (!$event->isPropagationStopped()) { \call_user_func_array($callback, [$event]); } if ($event->isPropagationStopped() && $throwOnPropStop) { throw $this->_createStoppedPropagationException( $this->__('Propagation has been stopped.'), 0, null, $event ); } return $event->getParam(0); }; }
php
{ "resource": "" }
q259094
Message.exportException
test
static function exportException(?\Throwable $e) { if($e === null) { return null; } $handler = \CharlotteDunois\Phoebe\ExceptionHandler::getInstance(); if($handler->handlesException($e)) { return $handler->exportException($e); } $trace = array(); foreach($e->getTrace() as $entry) { if(isset($entry['args'])) { foreach($entry['args'] as $key => $arg) { $entry['args'][$key] = static::exportTraceArgs($arg); } } else { $entry['args'] = array(); } $trace[] = $entry; } return array( 'class' => \get_class($e), 'message' => $e->getMessage(), 'code' => $e->getCode(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $trace, 'previous' => static::exportException($e->getPrevious()) ); }
php
{ "resource": "" }
q259095
Message.importException
test
static function importException(array $export, ?array $args = null) { if(!empty($export['phoebeExceptionHandler'])) { return \CharlotteDunois\Phoebe\ExceptionHandler::getInstance()->importException($export); } if($args === null) { $args = array($export['message'], $export['code']); } $args[] = (!empty($export['previous']) ? static::importException($export['previous']) : null); $class = new \ReflectionClass($export['class']); $err = $class->newInstanceArgs($args); $prop = $class->getProperty('file'); $prop->setAccessible(true); $prop->setValue($err, $export['file']); $prop = $class->getProperty('line'); $prop->setAccessible(true); $prop->setValue($err, $export['line']); if($class->hasProperty('trace')) { $prop = $class->getProperty('trace'); $prop->setAccessible(true); $prop->setValue($err, $export['trace']); } else { $parent = $class; while($parent = $parent->getParentClass()) { if($parent->hasProperty('trace')) { $prop = $parent->getProperty('trace'); $prop->setAccessible(true); $prop->setValue($err, $export['trace']); break; } } } return $err; }
php
{ "resource": "" }
q259096
RemoveWpHookCapableTrait._removeWpHook
test
protected function _removeWpHook($name, callable $handler, $priority = null) { $name = $this->_normalizeString($name); $priority = ($priority === null) ? $this->_getWpHookDefaultPriority() : $this->_normalizeInt($priority); \remove_filter($name, $handler, $priority); }
php
{ "resource": "" }
q259097
ReplaceWpHookCapableTrait._replaceWpHook
test
protected function _replaceWpHook($hook) { global $wp_filter; if (!isset($wp_filter[$hook])) { return; } $wp_filter[$hook] = $this->_createWpHookReplacement($wp_filter[$hook]); }
php
{ "resource": "" }
q259098
Worker.getStacked
test
function getStacked() { $stack = $this->stack->count(); $stack += (int) $this->bag->currentlyBusy; return $stack; }
php
{ "resource": "" }
q259099
Worker.clearRefBag
test
function clearRefBag(int $timeout) { $time = \time() - $timeout; foreach($this->refBag as $id => $timestamp) { if($timestamp <= $time) { unset($this->refBag[$id]); } } if(\count($this->refBag) === 0 && $this->stack->count() === 0) { $this->bag->lastEmptyStack = \time(); $this->bag->currentlyBusy = false; $msg = new \CharlotteDunois\Phoebe\Message('internal-worker-stack-free', null); $this->sendMessageToPool($msg); } }
php
{ "resource": "" }