xero-8.x-2.x-dev/src/Form/SettingsForm.php

src/Form/SettingsForm.php
<?php

namespace Drupal\xero\Form;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Drupal\Core\Url;
use Radcliffe\Xero\XeroProvider;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Xero API module configuration form.
 *
 * This allows the user to configure the site as a Xero application.
 */
class SettingsForm extends ConfigFormBase implements ContainerInjectionInterface {

  /**
   * Logger channel for Xero module.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   */
  protected $logger;

  /**
   * The private temp store.
   *
   * @var \Drupal\Core\TempStore\PrivateTempStore
   */
  protected $tempStore;

  /**
   * Initialization method.
   *
   * Inject dependencies into the form except for XeroClient because we want to
   * handle errors properly instead of failing and exploding spectacularly.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config.factory service.
   * @param \Drupal\Core\Config\TypedConfigManagerInterface $typedConfigManager
   *   The config.typed service.
   * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
   *   Logger channel factory for logging.
   * @param \Drupal\Core\TempStore\PrivateTempStoreFactory $tempStoreFactory
   *   The tempstore.private service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, TypedConfigManagerInterface $typedConfigManager, LoggerChannelFactoryInterface $logger_factory, PrivateTempStoreFactory $tempStoreFactory) {
    parent::__construct($config_factory, $typedConfigManager);

    $this->logger = $logger_factory->get('xero');
    $this->tempStore = $tempStoreFactory->get('xero.auth');
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // Get the configuration from ConfigFormBase::config().
    $config = self::config('xero.settings');

    $consumer_id = $config->get('oauth.consumer_key');
    $consumer_secret = $config->get('oauth.consumer_secret');
    $needsConfig = empty($consumer_id) || empty($consumer_secret);

    // Open the fieldset if there was a problem loading the library.
    $form['oauth'] = [
      '#type' => 'details',
      '#title' => $this->t('Xero OAuth 2.0 Configuration'),
      '#description' => 'The configuration here must match exactly that given for your Xero application in <a href="https://developer.xero.com/myapps">Xero\'s developer portal</a>.',
      '#open' => $needsConfig,
      '#tree' => TRUE,
    ];

    $redirectUri = Url::fromRoute('xero.authorize');
    $redirectUri->setAbsolute(TRUE);
    $redirectUri->setOption('https', TRUE);
    $form['oauth']['redirect_uri'] = [
      '#type' => 'textfield',
      '#title' => $this->t('OAuth 2.0 redirect URI'),
      '#default_value' => $redirectUri->toString(),
      '#disabled' => TRUE,
    ];

    $form['oauth']['consumer_key'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Client id'),
      '#default_value' => $config->get('oauth.consumer_key'),
      '#required' => TRUE,
    ];

    $form['oauth']['consumer_secret'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Client secret'),
      '#default_value' => $config->get('oauth.consumer_secret'),
      '#required' => TRUE,
    ];

    $form = parent::buildForm($form, $form_state);

    $form['actions']['authorize'] = [
      '#type' => 'submit',
      '#value' => $this->t('Authorize'),
      '#submit' => [[$this, 'authorize']],
      '#button_type' => 'secondary',
      '#access' => !$needsConfig,
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Sets configuration only if there are changes to save.
    $config = self::config('xero.settings');
    $form_state_values = $form_state->getValues();

    parent::submitForm($form, $form_state);

    $config
      ->set('oauth.consumer_key', $form_state_values['oauth']['consumer_key'])
      ->set('oauth.consumer_secret', $form_state_values['oauth']['consumer_secret'])
      ->set('oauth.redirect_uri', $form_state_values['oauth']['redirect_uri'])
      ->save();
  }

  /**
   * Submit callback for authorizing the site to Xero.
   *
   * @param array &$form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $formState
   *   The form state.
   *
   * @throws \Drupal\Core\TempStore\TempStoreException
   */
  public function authorize(array &$form, FormStateInterface $formState) {
    // Get configuration with overrides.
    $config = $this->configFactory->get('xero.settings');

    // Creates a new OAuth2 provider with the new consumer id/secret and sets
    // the redirect URL to this site's URL.
    $provider = new XeroProvider([
      'clientId' => $config->get('oauth.consumer_key'),
      'clientSecret' => $config->get('oauth.consumer_secret'),
      'redirectUri' => $config->get('oauth.redirect_uri'),
    ]);

    $provider_options = [
      'scope' => XeroProvider::getValidScopes('accounting'),
      'destination' => 'xero.configure',
    ];
    $response = new TrustedRedirectResponse($provider->getAuthorizationUrl($provider_options));
    $this->tempStore->set('state', $provider->getState());
    $this->tempStore->set('global', TRUE);
    $formState->setResponse($response);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('config.typed'),
      $container->get('logger.factory'),
      $container->get('tempstore.private')
    );
  }

}

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

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