Swap the subscription to a new Stripe plan.

@param string $plan

@return $this
554192
public function swap(string $plan)
    {
        $subscription = $this->asStripeSubscription();

        $subscription->plan = $plan;

        $subscription->prorate = $this->prorate;

        if (!is_null($this->billingCycleAnchor)) {
            $subscription->billingCycleAnchor = $this->billingCycleAnchor;
        }

        // If no specific trial end date has been set, the default behavior should be
        // to maintain the current trial state, whether that is "active" or to run
        // the swap out with the exact number of days left on this current plan.
        if ($this->onTrial()) {
            $subscription->trial_end = $this->trial_ends_at->getTimestamp();
        } else {
            $subscription->trial_end = 'now';
        }

        // Again, if no explicit quantity was set, the default behaviors should be to
        // maintain the current quantity onto the new plan. This is a sensible one
        // that should be the expected behavior for most developers with Stripe.
        if ($this->quantity) {
            $subscription->quantity = $this->quantity;
        }

        $subscription->save();

        $this->user->invoice();

        $this->stripe_plan = $plan;
        $this->ends_at = null;
        $this->save();

        return $this;
    }
514752
private function _handleSubscriptionUpdated(array $data)
    {
        $stripeSubscription = $data['data']['object'];
        $canceledAt = $data['data']['object']['canceled_at'];

        $subscription = Subscription::find()->reference($stripeSubscription['id'])->one();

        if (!$subscription) {
            Craft::warning('Subscription with the reference “' . $stripeSubscription['id'] . '” not found when processing webhook ' . $data['id'], 'stripe');

            return;
        }

        // See if we care about this subscription at all
        if ($subscription) {

            $subscription->isCanceled = (bool)$canceledAt;
            $subscription->dateCanceled = $canceledAt ? DateTimeHelper::toDateTime($canceledAt) : null;
            $subscription->nextPaymentDate = DateTimeHelper::toDateTime($data['data']['object']['current_period_end']);

            $planReference = $data['data']['object']['plan']['id'];
            $plan = Commerce::getInstance()->getPlans()->getPlanByReference($planReference);

            if ($plan) {
                $subscription->planId = $plan->id;
            } else {
                Craft::warning($subscription->reference . ' was switched to a plan on Stripe that does not exist on this Site. (event "' . $data['id'] . '")', 'stripe');
            }

            Commerce::getInstance()->getSubscriptions()->updateSubscription($subscription);
        }
    }
583019
public function addSubscription(StripeLocalSubscription $subscription)
    {
        // If the subscription is already set
        if (false === $this->subscriptions->contains($subscription)) {
            // Add the subscription to the collection
            $this->subscriptions->add($subscription);
        }

        return $this;
    }
318890
protected static function remove_archived_user_competencies_in_plan($plan) {
        $competencies = $plan->get_competencies();
        $usercompetenciesplan = user_competency_plan::get_multiple($plan->get('userid'), $plan->get('id'), $competencies);

        foreach ($usercompetenciesplan as $ucpkey => $ucp) {
            $ucp->delete();
        }
    }
91614
public function prev($offset = 1)
    {
        $prevDateTime = clone $this->startDateTime;
        $prevDateTime->modify('-'.abs($offset).' months');
        return new Month($prevDateTime);
    }
76402
public static function setProvider($option = '')
    {
        // Set default provider.
        if (empty($option) || ($option != 'adaptive_payments') || ($option == 'express_checkout')) {
            self::$provider = new ExpressCheckout();
        } else {
            self::$provider = new AdaptivePayments();
        }

        return self::getProvider();
    }
1097599
public function rollback($savepoint = null){
		$this->connection->getDriver()->rollback($savepoint);
		$this->notifyObservers(ObserverInterface::ROLLBACK);
		return $this;
	}
231222
function swap (callable $fn)
  {
    $this->pack ();
    $this->data = $fn ($this->data);
    return $this;
  }
783853
protected function swapAcrossFrequencies($plan): self
    {
        $currentPlan = BraintreeService::findPlan($this->braintree_plan);

        $discount = $this->switchingToMonthlyPlan($currentPlan, $plan)
                                ? $this->getDiscountForSwitchToMonthly($currentPlan, $plan)
                                : $this->getDiscountForSwitchToYearly();

        $options = [];

        if ($discount->amount > 0 && $discount->numberOfBillingCycles > 0) {
            $options = ['discounts' => ['add' => [
                [
                    'inheritedFromId' => 'plan-credit',
                    'amount' => (float) $discount->amount,
                    'numberOfBillingCycles' => $discount->numberOfBillingCycles,
                ],
            ]]];
        }

        $this->cancelNow();

        return $this->owner->newSubscription($this->name, $plan->id)
            ->skipTrial()
            ->create(null, [], $options);
    }
67914
public SubscriptionSchedule cancel() throws StripeException {
    return cancel((Map<String, Object>) null, (RequestOptions) null);
  }
294499
public function setPackage($package, $upgraded = null)
    {
        $this->currency = get_config_value('subscriptions.currency', 'US');
        $this->itemName = $package->name;
        $this->itemId = $package->id;
        $this->itemAmount = $package->price;
        $this->duration = $package->duration;
        $this->billingPeriod = $package->billingPeriod;
        $this->recurring = $package->recurring;

        if ($upgraded) {
            $this->duration = max(0, $package->duration - $upgraded->duration);
            $this->itemAmount = max(0, $package->price - $upgraded->price);
            $this->upgrade = true;
        }

        $this->_package = $package;

        return $this;
    }
234595
public function setPolicy(array $policy): self
    {
        $this->setModule($policy['module']);
        $this->setFunction($policy['function']);

        return $this;
    }
1235274
public function reconfigure(array $options = []): self
    {
        /** @var string $opt */
        /** @var string $val */
        foreach ($options as $opt => $val) {
            switch ($opt) {
                case 'formIndex':
                case 'formToken':
                case 'sessionIndex':
                case 'useNativeSession':
                case 'recycle_after':
                case 'hmac_ip':
                case 'expire_old':
                    /** @psalm-suppress MixedAssignment */
                    $this->$opt = $val;
                    break;
                case 'hashAlgo':
                    if (\in_array($val, \hash_algos(), true)) {
                        $this->hashAlgo = (string) $val;
                    }
                    break;
                case 'lock_type':
                    if (\in_array($val, array('REQUEST_URI','PATH_INFO'), true)) {
                        $this->lock_type = (string) $val;
                    }
                    break;
            }
        }
        return $this;
    }
751539
public function removeExchangeRateProvider(ExchangeRateProvider $provider) : self
    {
        $hash = spl_object_hash($provider);
        unset($this->providers[$hash]);

        return $this;
    }
1153226
public function addExchangeRateProvider(ExchangeRateProvider $provider) : self
    {
        $hash = spl_object_hash($provider);
        $this->providers[$hash] = $provider;

        return $this;
    }
289104
public function add($method)
    {
        if (is_array($method)) {
            $this->collection[] = new DeliveryMethod($method);
        } elseif (is_object($method) && $method instanceof DeliveryMethod) {
            $this->collection[] = $method;
        }

        return $this;
    }
892014
public function cancel()
    {
        $subscription = $this->asBraintreeSubscription();

        if ($this->onTrial()) {
            BraintreeSubscription::cancel($subscription->id);

            $this->markAsCancelled();
        } else {
            BraintreeSubscription::update($subscription->id, [
                'numberOfBillingCycles' => $subscription->currentBillingCycle,
            ]);

            $this->ends_at = $subscription->billingPeriodEndDate;

            $this->save();
        }

        return $this;
    }