You are here

class Fixed in Commerce Recurring Framework 8

Provides a fixed interval billing schedule.

Billing periods generated by this plugin always start at the beginning of the configured interval. For example, if a monthly subscription is opened on Oct 12th, the generated billing period will be Oct 1st - Nov 1st.

Monthly intervals can have a custom start day (Oct 3rd - Nov 3rd, etc). Yearly intervals can have a custom start month/day (Aug 6th - Aug 6th, etc).

Plugin annotation


@CommerceBillingSchedule(
  id = "fixed",
  label = @Translation("Fixed interval"),
)

Hierarchy

Expanded class hierarchy of Fixed

1 file declares its use of Fixed
FixedTest.php in tests/src/Kernel/Plugin/Commerce/BillingSchedule/FixedTest.php

File

src/Plugin/Commerce/BillingSchedule/Fixed.php, line 25

Namespace

Drupal\commerce_recurring\Plugin\Commerce\BillingSchedule
View source
class Fixed extends IntervalBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return parent::defaultConfiguration() + [
      'start_month' => 1,
      'start_day' => 1,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $form['start_month'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Start month'),
      '#description' => $this
        ->t('The month in which the billing period will start.'),
      '#options' => DateHelper::monthNames(TRUE),
      '#default_value' => $this->configuration['start_month'],
      '#states' => [
        'visible' => [
          ':input[name="configuration[fixed][interval][unit]"]' => [
            'value' => 'year',
          ],
        ],
      ],
    ];
    $form['start_day'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Start day'),
      '#description' => $this
        ->t('The day on which the billing period will start.'),
      '#options' => DateHelper::days(TRUE),
      '#default_value' => $this->configuration['start_day'],
      '#states' => [
        'visible' => [
          ':input[name="configuration[fixed][interval][unit]"]' => [
            [
              'value' => 'month',
            ],
            [
              'value' => 'year',
            ],
          ],
        ],
      ],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);
    if (!$form_state
      ->getErrors()) {
      $interval_unit = $this->configuration['interval']['unit'];
      $values = $form_state
        ->getValue($form['#parents']);
      $this->configuration['start_month'] = 1;
      $this->configuration['start_day'] = 1;
      if (in_array($interval_unit, [
        'month',
        'year',
      ])) {
        if ($interval_unit == 'year') {
          $this->configuration['start_month'] = $values['start_month'];
        }
        $this->configuration['start_day'] = $values['start_day'];
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function generateFirstBillingPeriod(DrupalDateTime $start_date) {

    // @todo $start_date->setTimezone($site_timezone)
    $interval = $this
      ->getInterval();
    $adjusted_start_date = $this
      ->adjustStartDate($start_date);
    return new BillingPeriod($adjusted_start_date, $interval
      ->add($adjusted_start_date));
  }

  /**
   * {@inheritdoc}
   */
  public function generateNextBillingPeriod(DrupalDateTime $start_date, BillingPeriod $billing_period) {
    $next_start_date = $billing_period
      ->getEndDate();
    return new BillingPeriod($next_start_date, $this
      ->getInterval()
      ->add($next_start_date));
  }

  /**
   * Adjusts the start date to the beginning of the configured interval.
   *
   * In addition to flooring the start date (so that May 15th becomes May 1st
   * for monthly intervals, etc), it also handles custom start months/days.
   *
   * @param \Drupal\Core\Datetime\DrupalDateTime $start_date
   *   The start date.
   *
   * @return \Drupal\Core\Datetime\DrupalDateTime
   *   The adjusted start date.
   */
  protected function adjustStartDate(DrupalDateTime $start_date) {
    $interval = $this
      ->getInterval();
    $adjusted_start_date = $interval
      ->floor($start_date);
    if (!in_array($interval
      ->getUnit(), [
      'month',
      'year',
    ])) {
      return $adjusted_start_date;
    }
    $start_year = $start_date
      ->format('Y');
    $start_month = $start_date
      ->format('m');
    if ($interval
      ->getUnit() == 'year') {
      $start_month = $this->configuration['start_month'];
    }
    $start_day = $this->configuration['start_day'];
    $adjusted_start_date
      ->setDate($start_year, $start_month, $start_day);

    // Further adjust the date if it is now in the future, to account for
    // customers subscribing before the custom start month/day (which puts
    // them in the previous billing period).
    if ($adjusted_start_date
      ->format('U') > $start_date
      ->format('U')) {
      $adjusted_start_date = $interval
        ->subtract($adjusted_start_date);
    }
    return $adjusted_start_date;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BillingScheduleBase::$entityId protected property The ID of the parent config entity.
BillingScheduleBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
BillingScheduleBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
BillingScheduleBase::getLabel public function Gets the billing schedule label. Overrides BillingScheduleInterface::getLabel
BillingScheduleBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
BillingScheduleBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
BillingScheduleBase::__construct public function Constructs a new BillingScheduleBase object. Overrides PluginBase::__construct
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
Fixed::adjustStartDate protected function Adjusts the start date to the beginning of the configured interval.
Fixed::buildConfigurationForm public function Form constructor. Overrides IntervalBase::buildConfigurationForm
Fixed::defaultConfiguration public function Gets default configuration for this plugin. Overrides IntervalBase::defaultConfiguration
Fixed::generateFirstBillingPeriod public function Generates the first billing period. Overrides BillingScheduleInterface::generateFirstBillingPeriod
Fixed::generateNextBillingPeriod public function Generates the next billing period. Overrides BillingScheduleInterface::generateNextBillingPeriod
Fixed::submitConfigurationForm public function Form submission handler. Overrides IntervalBase::submitConfigurationForm
IntervalBase::allowTrials public function Checks whether the billing schedule allows trials. Overrides BillingScheduleInterface::allowTrials
IntervalBase::generateTrialPeriod public function Generates the trial period. Overrides BillingScheduleInterface::generateTrialPeriod
IntervalBase::getInterval protected function Gets the current interval.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.