bm-1.0.x-dev/src/Form/BookingGenerator.php

src/Form/BookingGenerator.php
<?php

namespace Drupal\bm\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use CommerceGuys\Addressing\AddressFormat\AddressFormatRepository;
use CommerceGuys\Addressing\Country\CountryRepository;
use CommerceGuys\Addressing\Subdivision\SubdivisionRepository;
/**
 * Configuration for Booking Generator.
 */
class BookingGenerator extends FormBase {


  /**
   * The entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The CountryRepository.
   *
   * @var \CommerceGuys\Addressing\Country\CountryRepository
   */
  protected $countryRepository;

  /**
   * The AddressFormatRepository.
   *
   * @var \CommerceGuys\Addressing\AddressFormat\AddressFormatRepository
   */
  protected $addressFormatRepository;

  /**
   * The SubdivisionRepository.
   *
   * @var \CommerceGuys\Addressing\Subdivision\SubdivisionRepository
   */
  protected $subdivisionRepository;

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager) {
    $this->entityTypeManager = $entityTypeManager;
    $this->countryRepository = new CountryRepository();
    $this->addressFormatRepository = new AddressFormatRepository();
    $this->subdivisionRepository = new SubdivisionRepository();
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
    );
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['bm_date_generator.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'bm_date_generator';
  }

  const LABEL_FORMAT = 'M d, Y h:i A';

  const VAL_DATE_FORMAT = 'Y-m-d';

  const VAL_TIME_FORMAT = 'H:i:s';

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {


// Get the country list (countryCode => name), in French.
// $countryList = $countryRepository->getList('EN');
// $country = $countryRepository->get('PH');
// $addressFormat = $addressFormatRepository->get('PH');

// foreach($states_place as $state) {
//   ksm($states_place->getChildren());
// }
    $form['bm'] = [
      '#type' => 'container',
      '#attributes' => [
        'id' => 'bm',
      ],
    ];

    $form['bm']['fieldset_dt'] = [
      '#type' => 'details',
      '#title' => $this->t('Booking Date Settings'),
      '#description' => $this->t('Dates will save in Structure > Taxonomy > Booking Dates'),
      '#open' => TRUE,
    ];

    $form['bm']['fieldset_dt']['sdate'] = [
      '#type' => 'datetime',
      '#title' => $this->t('Start Date'),
      '#description' => $this->t('No value means start date is current date time.'),
    ];

    $form['bm']['fieldset_dt']['edate'] = [
      '#type' => 'datetime',
      '#title' => $this->t('End Date'),
      '#description' => $this->t('No value means 1 year span.'),
    ];

    $form['bm']['fieldset_dt']['interval'] = [
      '#type' => 'number',
      '#title' => $this->t('Interval (in hours)'),
      '#default_value' => '24',
    ];

    $form['bm']['fieldset_dt']['btn'] = [
      '#type' => 'markup',
      '#markup' => '<a href="/admin/structure/taxonomy/manage/bm_booking_dates/overview" class="button">Goto Booking Dates</a>',
      '#allowed_tags' => ['a'],
    ];


    $form['bm']['fieldset_place'] = [
      '#type' => 'details',
      '#title' => $this->t('Address Settings'),
      '#description' => $this->t('Dates will save in Structure > Taxonomy > Booking Place'),
      '#open' => TRUE,
    ];

    $form['bm']['fieldset_place']['country'] = [
      '#type' => 'select',
      '#title' => $this->t('Select Country'),
      '#options' => $this->countryRepository->getList('EN'),
      '#description' => $this->t('Generate Place based from country.'),
    ];

    $form['bm']['fieldset_place']['btn'] = [
      '#type' => 'markup',
      '#markup' => '<a href="/admin/structure/taxonomy/manage/bm_place/overview" class="button">Goto Booking Place</a>',
      '#allowed_tags' => ['a'],
    ];

    $form['bm']['actions']['place'] = [
      '#submit' => [[$this, 'generate_place']],
      '#type' => 'submit',
      '#value' => $this->t('Generate Place'),
    ];

    // $form['bm']['actions']['date'] = [
    //   '#submit' => [[$this, 'generate_date']],
    //   '#type' => 'submit',
    //   '#value' => $this->t('Generate Date'),
    // ];

    unset($form['bm']['fieldset_dt']);
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function generate_date(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    $start_date = $values['sdate'] ? $values['sdate']->getPhpDateTime()->getTimestamp() : time();
    $end_date = $values['edate'] ? $values['edate']->getPhpDateTime()->getTimestamp() : FALSE;
    $interval = $values['interval'] ? $values['interval'] : 24;
    $dates = $this->getDates($start_date, $end_date, $interval);
    $process['operations'][] = [
      [$this, 'processBatch'], [$dates],
    ];

    $process['finished'] = [$this, 'finished'];
    batch_set($process);

  }

  /**
   * {@inheritdoc}
   */
  public function generate_place(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    $country = $values['country'];
    $states = $this->subdivisionRepository->getAll([$country]);
    $term = $this->entityTypeManager->getStorage('taxonomy_term');
    foreach ($states as $state) {
      $term->create([
        'name' => $state->getName(),
        'vid' => 'bm_place'
      ])->save();
    }
    $this->messenger()->addMessage($this->t('Success'));
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {}

  /**
   * {@inheritdoc}
   */
  protected function getDates($start_date, $end_date, $interval) {
    if ($start_date > $end_date && !empty($end_date)) {
      $tmp_date = $start_date;
      $start_date = $end_date;
      $end_date = $tmp_date;
    }
    // Convert hours to seconds;.
    $interval = $interval * 3600;
    $start_ts = $start_date;
    $end_count = 365;
    if (!empty($end_date)) {
      $sec = $end_date - $start_date;
      $end_count = (int) ceil($sec / $interval);
    }
    $dates = [];
    $prev = $start_ts;
    for ($i = 1; $i < $end_count; ++$i) {
      $dates[date(self::LABEL_FORMAT, $prev)] = date(self::VAL_DATE_FORMAT, $prev) . 'T' . date(self::VAL_TIME_FORMAT, $prev);
      $prev += $interval;
    }
    return $dates;
  }

  /**
   * {@inheritdoc}
   */
  public function processBatch($contents, array &$context) {
    if (!isset($context['sandbox']['progress'])) {
      $context['sandbox']['progress'] = 0;
      $context['sandbox']['max'] = 1;
    }

    $term = $this->entityTypeManager->getStorage('taxonomy_term');
    foreach ($contents as $label => $datetime) {
      // Skip if datetime already exists.
     if (empty($term->loadByProperties(['field_bm_date' => $datetime]))) {
        $term->create([
          'name' => $label,
          'vid' => 'bm_booking_dates',
          'field_bm_date' => $datetime,
        ])->save();
      }
    }

    $context['sandbox']['progress']++;
    $context['message'] = t('Import entity %index out of %max', ['%index' => $context['sandbox']['progress'], '%max' => $context['sandbox']['max']]);

    if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
      $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function finished($success, array $results, array $operations) {
    $this->messenger()->addMessage($this->t('Success'));
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc