You are here

class BrightcoveAPIClientForm in Brightcove Video Connect 8

Same name and namespace in other branches
  1. 8.2 src/Form/BrightcoveAPIClientForm.php \Drupal\brightcove\Form\BrightcoveAPIClientForm
  2. 3.x src/Form/BrightcoveAPIClientForm.php \Drupal\brightcove\Form\BrightcoveAPIClientForm

Class BrightcoveAPIClientForm.

@package Drupal\brightcove\Form

Hierarchy

Expanded class hierarchy of BrightcoveAPIClientForm

File

src/Form/BrightcoveAPIClientForm.php, line 28

Namespace

Drupal\brightcove\Form
View source
class BrightcoveAPIClientForm extends EntityForm {

  /**
   * The config for brightcove.settings.
   *
   * @var \Drupal\Core\Config\Config
   */
  protected $config;

  /**
   * The brightcove_player storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $playerStorage;

  /**
   * The player queue object.
   *
   * @var \Drupal\Core\Queue\QueueInterface
   */
  protected $playerQueue;

  /**
   * The custom field queue object.
   *
   * @var \Drupal\Core\Queue\QueueInterface
   */
  protected $customFieldQueue;

  /**
   * The subscriptions queue object.
   *
   * @var \Drupal\Core\Queue\QueueInterface
   */
  protected $subscriptionsQueue;

  /**
   * Query factory.
   *
   * @var \Drupal\Core\Entity\Query\QueryFactory
   */
  protected $queryFactory;

  /**
   * Key/Value expirable store.
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
   */
  protected $keyValueExpirableStore;

  /**
   * Constructs a new BrightcoveAPIClientForm.
   *
   * @param \Drupal\Core\Config\Config $config
   *   The config for brightcove.settings.
   * @param \Drupal\Core\Entity\EntityStorageInterface $player_storage
   *   Player entity storage.
   * @param \Drupal\Core\Queue\QueueInterface $player_queue
   *   Player queue.
   * @param \Drupal\Core\Queue\QueueInterface $custom_field_queue
   *   Custom field queue.
   * @param \Drupal\Core\Queue\QueueInterface $subscriptions_queue
   *   Custom field queue.
   * @param \Drupal\Core\Entity\Query\QueryFactory $query_factory
   *   Query factory.
   * @param \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface $key_value_expirable_store
   *   Key/Value expirable store for "brightcove_access_token".
   */
  public function __construct(Config $config, EntityStorageInterface $player_storage, QueueInterface $player_queue, QueueInterface $custom_field_queue, QueueInterface $subscriptions_queue, QueryFactory $query_factory, KeyValueStoreExpirableInterface $key_value_expirable_store) {
    $this->config = $config;
    $this->playerStorage = $player_storage;
    $this->playerQueue = $player_queue;
    $this->customFieldQueue = $custom_field_queue;
    $this->subscriptionsQueue = $subscriptions_queue;
    $this->queryFactory = $query_factory;
    $this->keyValueExpirableStore = $key_value_expirable_store;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory')
      ->getEditable('brightcove.settings'), $container
      ->get('entity_type.manager')
      ->getStorage('brightcove_player'), $container
      ->get('queue')
      ->get('brightcove_player_queue_worker'), $container
      ->get('queue')
      ->get('brightcove_custom_field_queue_worker'), $container
      ->get('queue')
      ->get('brightcove_subscriptions_queue_worker'), $container
      ->get('entity.query'), $container
      ->get('keyvalue.expirable')
      ->get('brightcove_access_token'));
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);

    /** @var \Drupal\brightcove\Entity\BrightcoveAPIClient $brightcove_api_client */
    $brightcove_api_client = $this->entity;

    // Don't even try reporting the status/error message of a new client.
    if (!$brightcove_api_client
      ->isNew()) {
      try {
        $brightcove_api_client
          ->authorizeClient();
        $status = $brightcove_api_client
          ->getClientStatus() ? $this
          ->t('OK') : $this
          ->t('Error');
      } catch (\Exception $e) {
        $status = $this
          ->t('Error');
      }
      $form['status'] = [
        '#type' => 'item',
        '#title' => t('Status'),
        '#markup' => $status,
      ];
      if ($brightcove_api_client
        ->getClientStatus() == 0) {
        $form['status_message'] = [
          '#type' => 'item',
          '#title' => t('Error message'),
          '#markup' => $brightcove_api_client
            ->getClientStatusMessage(),
        ];
      }
    }
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Label'),
      '#maxlength' => 255,
      '#default_value' => $brightcove_api_client
        ->label(),
      '#description' => $this
        ->t('A label to identify the API Client (authentication credentials).'),
      '#required' => TRUE,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $brightcove_api_client
        ->id(),
      '#machine_name' => [
        'exists' => '\\Drupal\\brightcove\\Entity\\BrightcoveAPIClient::load',
      ],
      '#disabled' => !$brightcove_api_client
        ->isNew(),
    ];
    $form['client_id'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Brightcove API Client ID'),
      '#description' => $this
        ->t('The Client ID of the Brightcove API Authentication credentials, available <a href=":link" target="_blank">here</a>.', [
        ':link' => 'https://studio.brightcove.com/products/videocloud/admin/oauthsettings',
      ]),
      '#maxlength' => 255,
      '#default_value' => $brightcove_api_client
        ->getClientId(),
      '#required' => TRUE,
    ];
    $form['secret_key'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Brightcove API Secret Key'),
      '#description' => $this
        ->t('The Secret Key associated with the Client ID above, only visible once when Registering New Application.'),
      '#maxlength' => 255,
      '#default_value' => $brightcove_api_client
        ->getSecretKey(),
      '#required' => TRUE,
    ];
    $form['account_id'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Brightcove Account ID'),
      '#description' => $this
        ->t('The number of one of the Brightcove accounts "selected for authorization" with the API Client above.'),
      '#maxlength' => 255,
      '#default_value' => $brightcove_api_client
        ->getAccountId(),
      '#required' => TRUE,
    ];
    $form['default_player'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Default player'),
      '#options' => BrightcovePlayer::getList($brightcove_api_client
        ->id()),
      '#default_value' => $brightcove_api_client
        ->getDefaultPlayer() ? $brightcove_api_client
        ->getDefaultPlayer() : BrightcoveAPIClient::DEFAULT_PLAYER,
      '#required' => TRUE,
    ];
    if ($brightcove_api_client
      ->isNew()) {
      $form['default_player']['#description'] = t('The rest of the players will be available after saving.');
    }

    // Count BrightcoveAPIClients.
    $api_clients_number = $this->queryFactory
      ->get('brightcove_api_client')
      ->count()
      ->execute();
    $form['default_client'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Default API Client'),
      '#description' => $this
        ->t('Enable to make this the default API Client.'),
      '#default_value' => $api_clients_number == 0 || $this->config
        ->get('defaultAPIClient') == $brightcove_api_client
        ->id(),
    ];
    return $form;
  }

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

      // Try to authorize client and save values on success.
      $client = Client::authorize($form_state
        ->getValue('client_id'), $form_state
        ->getValue('secret_key'));

      // Test account ID.
      $cms = new CMS($client, $form_state
        ->getValue('account_id'));
      $cms
        ->countVideos();
      $this->keyValueExpirableStore
        ->setWithExpire($form_state
        ->getValue('id'), $client
        ->getAccessToken(), intval($client
        ->getExpiresIn()) - 30);
    } catch (AuthenticationException $e) {
      $form_state
        ->setErrorByName('client_id', $e
        ->getMessage());
      $form_state
        ->setErrorByName('secret_key');
    } catch (APIException $e) {
      $form_state
        ->setErrorByName('account_id', $e
        ->getMessage());
    }
  }

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

    /** @var \Drupal\brightcove\Entity\BrightcoveAPIClient $entity */
    $entity = $this->entity;
    $client = new Client($this->keyValueExpirableStore
      ->get($form_state
      ->getValue('id')));
    $cms = new CMS($client, $form_state
      ->getValue('account_id'));

    /** @var \Brightcove\Object\CustomFields $video_fields */
    $video_fields = $cms
      ->getVideoFields();
    $entity
      ->setMaxCustomFields($video_fields
      ->getMaxCustomFields());
    foreach ($video_fields
      ->getCustomFields() as $custom_field) {

      // Create queue item.
      $this->customFieldQueue
        ->createItem([
        'api_client_id' => $this->entity
          ->id(),
        'custom_field' => $custom_field,
      ]);
    }
    parent::submitForm($form, $form_state);
    if ($entity
      ->isNew()) {

      // Get Players the first time when the API client is being saved.
      $pm = new PM($client, $form_state
        ->getValue('account_id'));
      $player_list = $pm
        ->listPlayers();
      $players = [];
      if (!empty($player_list) && !empty($player_list
        ->getItems())) {
        $players = $player_list
          ->getItems();
      }
      foreach ($players as $player) {

        // Create queue item.
        $this->playerQueue
          ->createItem([
          'api_client_id' => $entity
            ->id(),
          'player' => $player,
        ]);
      }

      // Get Custom fields the first time when the API client is being saved.

      /** @var \Brightcove\Object\CustomFields $video_fields */
      $video_fields = $cms
        ->getVideoFields();
      foreach ($video_fields
        ->getCustomFields() as $custom_field) {

        // Create queue item.
        $this->customFieldQueue
          ->createItem([
          'api_client_id' => $entity
            ->id(),
          'custom_field' => $custom_field,
        ]);
      }

      // Create new default subscription.
      $subscription = new BrightcoveSubscription(TRUE);
      $subscription
        ->setStatus(FALSE)
        ->setApiClient($entity)
        ->setEndpoint(BrightcoveUtil::getDefaultSubscriptionUrl())
        ->setEvents([
        'video-change',
      ])
        ->save();

      // Get Subscriptions the first time when the API client is being saved.
      $this->subscriptionsQueue
        ->createItem($entity
        ->id());
    }
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $brightcove_api_client = $this->entity;
    $status = $brightcove_api_client
      ->save();
    switch ($status) {
      case SAVED_NEW:
        drupal_set_message($this
          ->t('Created the %label Brightcove API Client.', [
          '%label' => $brightcove_api_client
            ->label(),
        ]));

        // Initialize batch.
        batch_set([
          'operations' => [
            [
              [
                BrightcoveUtil::class,
                'runQueue',
              ],
              [
                'brightcove_player_queue_worker',
              ],
            ],
            [
              [
                BrightcoveUtil::class,
                'runQueue',
              ],
              [
                'brightcove_custom_field_queue_worker',
              ],
            ],
            [
              [
                BrightcoveUtil::class,
                'runQueue',
              ],
              [
                'brightcove_subscriptions_queue_worker',
              ],
            ],
            [
              [
                BrightcoveUtil::class,
                'runQueue',
              ],
              [
                'brightcove_subscription_queue_worker',
              ],
            ],
          ],
        ]);
        break;
      default:
        drupal_set_message($this
          ->t('Saved the %label Brightcove API Client.', [
          '%label' => $brightcove_api_client
            ->label(),
        ]));
    }
    if ($form_state
      ->getValue('default_client')) {
      $this->config
        ->set('defaultAPIClient', $brightcove_api_client
        ->id())
        ->save();
    }
    $form_state
      ->setRedirectUrl($brightcove_api_client
      ->urlInfo('collection'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BrightcoveAPIClientForm::$config protected property The config for brightcove.settings.
BrightcoveAPIClientForm::$customFieldQueue protected property The custom field queue object.
BrightcoveAPIClientForm::$keyValueExpirableStore protected property Key/Value expirable store.
BrightcoveAPIClientForm::$playerQueue protected property The player queue object.
BrightcoveAPIClientForm::$playerStorage protected property The brightcove_player storage.
BrightcoveAPIClientForm::$queryFactory protected property Query factory.
BrightcoveAPIClientForm::$subscriptionsQueue protected property The subscriptions queue object.
BrightcoveAPIClientForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
BrightcoveAPIClientForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
BrightcoveAPIClientForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
BrightcoveAPIClientForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides EntityForm::submitForm
BrightcoveAPIClientForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
BrightcoveAPIClientForm::__construct public function Constructs a new BrightcoveAPIClientForm.
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
EntityForm::$entity protected property The entity being used by this form. 7
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::__get public function
EntityForm::__set public function
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
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.
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.
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.