You are here

class Settings in Google API PHP Client 8

Google API Settings.

Hierarchy

Expanded class hierarchy of Settings

1 string reference to 'Settings'
google_api_client.routing.yml in ./google_api_client.routing.yml
google_api_client.routing.yml

File

src/Form/Settings.php, line 16

Namespace

Drupal\google_api_client\Form
View source
class Settings extends ConfigFormBase {

  /**
   * Google API Client.
   *
   * @var \Drupal\google_api_client\Service\GoogleApiClient
   */
  private $googleApiClient;

  /**
   * Settings constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   Config Factory.
   * @param \Drupal\google_api_client\Service\GoogleApiClient $googleApiClient
   *   Google Api Client.
   */
  public function __construct(ConfigFactoryInterface $config_factory, GoogleApiClient $googleApiClient) {
    parent::__construct($config_factory);
    $this->googleApiClient = $googleApiClient;
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('google_api_client.settings');
    $tokenConf = $this
      ->config('google_api_client.tokens');
    $options = [
      'attributes' => [
        'target' => '_blank',
      ],
    ];
    $form['client'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Client Settings'),
    ];
    $form['client']['help'] = [
      '#type' => '#markup',
      '#markup' => $this
        ->t('To get your Client Credentials, you need to register your application. See details on @link.', [
        '@link' => Link::fromTextAndUrl('https://developers.google.com/api-client-library/php/auth/web-app', Url::fromUri('https://developers.google.com/api-client-library/php/auth/web-app'))
          ->toString(),
      ]),
    ];
    $form['client']['credentials'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Client Credentials'),
      '#default_value' => $config
        ->get('credentials'),
      '#required' => TRUE,
      '#placeholder' => $this
        ->t('Example: {"web":{"client_id":"example.apps.googleusercontent.com","project_id":"example","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"example","redirect_uris":["http://example.com/google_api_client/callback"],"javascript_origins":["http://example.com"]}}'),
    ];
    $linkScopes = Link::fromTextAndUrl('click here to learn more', Url::fromUri('https://developers.google.com/identity/protocols/googlescopes', $options))
      ->toString();
    $form['client']['scopes'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Client Scopes'),
      '#default_value' => $config
        ->get('scopes'),
      '#required' => TRUE,
      '#placeholder' => $this
        ->t('Example: https://www.googleapis.com/auth/cse'),
      '#description' => $this
        ->t('Add one scope per line. OAuth 2.0 Scopes for Google APIs, @link. After changing scopes, you have to request new tokens.', [
        '@link' => $linkScopes,
      ]),
    ];
    if ($config
      ->get('credentials') != '') {

      // Failure to get URL might be because of invalid client credentials.
      try {
        $url = $this
          ->accessUrl();
      } catch (\Exception $e) {
        $msg = $this
          ->t('Failure to use provided client credentials. Error message: <q>@error</q>', [
          '@error' => $e
            ->getMessage(),
        ]);
        $this
          ->messenger()
          ->addError($msg);
      }
    }
    if (isset($url)) {
      $link = Link::fromTextAndUrl('click here', Url::fromUri($url, $options))
        ->toString();

      // Just check if any of the tokens are set, if not set a message.
      if ($tokenConf
        ->get('google_access_token') == NULL && $tokenConf
        ->get('google_refresh_token') == NULL) {
        $msg = $this
          ->t('Access and Refresh Tokens are not set, to get your Tokens, @link.', [
          '@link' => $link,
        ]);
        $this
          ->messenger()
          ->addError($msg);
      }

      // TODO Figure out a nicer way to display the link. Maybe a button?
      $form['client']['tokens'] = [
        '#type' => 'details',
        '#title' => $this
          ->t('Access and Refresh Tokens'),
        '#description' => $this
          ->t('To get your Tokens, @link.', [
          '@link' => $link,
        ]),
        '#open' => TRUE,
        '#access' => TRUE,
      ];
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this
      ->config('google_api_client.settings')
      ->set('credentials', $form_state
      ->getValue('credentials'))
      ->set('scopes', $form_state
      ->getValue('scopes'))
      ->save();
    parent::submitForm($form, $form_state);
  }

  /**
   * Generate the Access Url.
   *
   * See details at
   * https://developers.google.com/identity/protocols/OAuth2WebServer?csw=1#formingtheurl.
   *
   * @return string
   *   URL.
   */
  private function accessUrl() {

    // This is required when developing and in need of refresh tokens.
    // Refresh Tokens are only sent if this is set to force.
    // Since we are explicitly asking the user to refresh tokens,
    // its best to force this.
    $this->googleApiClient->googleClient
      ->setApprovalPrompt("force");

    // Generate a URL to request access from Google's OAuth 2.0 server.
    return $this->googleApiClient->googleClient
      ->createAuthUrl();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
Settings::$googleApiClient private property Google API Client.
Settings::accessUrl private function Generate the Access Url.
Settings::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
Settings::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
Settings::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
Settings::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
Settings::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
Settings::__construct public function Settings constructor. Overrides ConfigFormBase::__construct
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.