You are here

class Bynder in Bynder 8

Provides media type plugin for Bynder.

Plugin annotation


@MediaType(
  id = "bynder",
  label = @Translation("Bynder"),
  description = @Translation("Provides business logic and metadata for Bynder.")
)

Hierarchy

Expanded class hierarchy of Bynder

7 files declare their use of Bynder
bynder.module in ./bynder.module
Provides bynder integration.
BynderFormatter.php in src/Plugin/Field/FieldFormatter/BynderFormatter.php
BynderMediaUsage.php in src/Controller/BynderMediaUsage.php
BynderSearch.php in src/Plugin/EntityBrowser/Widget/BynderSearch.php
BynderUpload.php in src/Plugin/EntityBrowser/Widget/BynderUpload.php

... See full list

8 string references to 'Bynder'
bynder.info.yml in ./bynder.info.yml
bynder.info.yml
bynder.links.menu.yml in ./bynder.links.menu.yml
bynder.links.menu.yml
BynderUploadWidgetTest::testUploadConfigurationForm in tests/src/FunctionalJavascript/BynderUploadWidgetTest.php
Tests upload configuration form.
bynder_help in ./bynder.module
Implements hook_help().
ConfigurationFormTest::testConfigurationForm in tests/src/FunctionalJavascript/ConfigurationFormTest.php
Tests the configuration form.

... See full list

File

src/Plugin/MediaEntity/Type/Bynder.php, line 31

Namespace

Drupal\bynder\Plugin\MediaEntity\Type
View source
class Bynder extends MediaTypeBase {

  /**
   * Bynder api service.
   *
   * @var \Drupal\bynder\BynderApiInterface
   *   Bynder api service.
   */
  protected $bynderApi;

  /**
   * Account proxy.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $accountProxy;

  /**
   * The url generator.
   *
   * @var \Drupal\Core\Routing\UrlGeneratorInterface
   */
  protected $urlGenerator;

  /**
   * Statically cached API response for a given asset.
   *
   * @var array
   */
  protected $apiResponse;

  /**
   * The logger factory service.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $logger;

  /**
   * The cache service.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cache;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * Used to track if an API request returned a timout error.
   *
   * @var bool
   */
  protected static $timoutDetected = FALSE;

  /**
   * Constructs a new class instance.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   Entity type manager service.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   Entity field manager service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The Config factory.
   * @param \Drupal\bynder\BynderApiInterface $bynder_api_service
   *   Bynder api service.
   * @param \Drupal\Core\Session\AccountProxyInterface $account_proxy
   *   Account proxy.
   * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
   *   The url generator service.
   * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger
   *   The logger factory service.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache
   *   The cache service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, ConfigFactoryInterface $config_factory, BynderApiInterface $bynder_api_service, AccountProxyInterface $account_proxy, UrlGeneratorInterface $url_generator, LoggerChannelFactoryInterface $logger, CacheBackendInterface $cache, TimeInterface $time) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $entity_field_manager, $config_factory
      ->get('media_entity.settings'));
    $this->bynderApi = $bynder_api_service;
    $this->accountProxy = $account_proxy;
    $this->urlGenerator = $url_generator;
    $this->logger = $logger;
    $this->cache = $cache;
    $this->configFactory = $config_factory;
    $this->time = $time;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'), $container
      ->get('entity_field.manager'), $container
      ->get('config.factory'), $container
      ->get('bynder_api'), $container
      ->get('current_user'), $container
      ->get('url_generator'), $container
      ->get('logger.factory'), $container
      ->get('cache.data'), $container
      ->get('datetime.time'));
  }

  /**
   * {@inheritdoc}
   */
  public function providedFields() {
    $fields = [
      'uuid' => $this
        ->t('ID'),
      'name' => $this
        ->t('Name'),
      'description' => $this
        ->t('Description'),
      'tags' => $this
        ->t('Tags'),
      'type' => $this
        ->t('Type'),
      'video_preview_urls' => $this
        ->t('Video preview urls'),
      'thumbnail_urls' => $this
        ->t('Thumbnail urls'),
      'width' => $this
        ->t('Width'),
      'height' => $this
        ->t('Height'),
      'created' => $this
        ->t('Date created'),
      'modified' => $this
        ->t('Data modified'),
      'propertyOptions' => $this
        ->t('Meta-property option IDs'),
    ];
    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'source_field' => '',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getField(MediaInterface $media, $name) {
    if (!($source_field = $this->configuration['source_field'])) {
      return FALSE;
    }
    if (!($media_uuid = $media->{$source_field}->value)) {
      return FALSE;
    }
    if ($name == 'uuid') {
      return $media_uuid;
    }
    if (!isset($this->apiResponse)) {
      try {

        // Check for cached data first, either set below or by
        // \Drupal\bynder\Plugin\EntityBrowser\Widget\BynderSearch::submit(),
        // to avoid extra API requests.
        if ($cache = $this->cache
          ->get('bynder_item_' . $media_uuid)) {
          $this->apiResponse = $cache->data;
        }
        elseif (!static::$timoutDetected) {
          $this->apiResponse = $this->bynderApi
            ->getMediaInfo($media_uuid);

          // Cache the response for the configured timeframe.
          $this->cache
            ->set('bynder_item_' . $media_uuid, $this->apiResponse, $this->time
            ->getRequestTime() + $this->configFactory
            ->get('bynder.settings')
            ->get('cache_lifetime'));
        }
      } catch (GuzzleException $e) {
        if ($e instanceof ConnectException) {
          $handler_context = $e
            ->getHandlerContext();
          if (isset($handler_context['errno']) && $handler_context['errno'] == 28) {
            static::$timoutDetected = TRUE;
          }
        }
        $this->logger
          ->get('bynder')
          ->error('Unable to fetch info about the asset represented by media @name (@id) with message @message.', [
          '@name' => $media
            ->label(),
          '@id' => $media
            ->id(),
          '@message' => $e
            ->getMessage(),
        ]);
        return FALSE;
      }
    }
    if (!empty($this->apiResponse)) {
      switch ($name) {
        case 'video_preview_urls':
          return isset($this->apiResponse['videoPreviewURLs']) ? $this->apiResponse['videoPreviewURLs'] : FALSE;
        case 'thumbnail_urls':
          return isset($this->apiResponse['thumbnails']) ? $this->apiResponse['thumbnails'] : FALSE;
        case 'created':
          return isset($this->apiResponse['dateCreated']) ? $this->apiResponse['dateCreated'] : FALSE;
        case 'modified':
          return isset($this->apiResponse['dateModified']) ? $this->apiResponse['dateModified'] : FALSE;
        default:
          return isset($this->apiResponse[$name]) ? $this->apiResponse[$name] : FALSE;
      }
    }
    return FALSE;
  }

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

    // Check the connection with bynder.
    try {
      $this->bynderApi
        ->getBrands();
    } catch (\Exception $exception) {
      if ($this->accountProxy
        ->hasPermission('administer bynder configuration')) {
        drupal_set_message($this
          ->t('Connecting with Bynder failed. Check if the configuration is set properly <a href=":url">here</a>.', [
          ':url' => $this->urlGenerator
            ->generateFromRoute('bynder.configuration_form'),
        ]), 'error');
      }
      else {
        drupal_set_message($this
          ->t('Something went wrong with the Bynder connection. Please contact the site administrator.'), 'error');
      }
    }

    /** @var \Drupal\media_entity\MediaBundleInterface $bundle */
    $bundle = $form_state
      ->getFormObject()
      ->getEntity();
    $options = [];
    $allowed_field_types = [
      'string',
      'string_long',
    ];
    foreach ($this->entityFieldManager
      ->getFieldDefinitions('media', $bundle
      ->id()) as $field_name => $field) {
      if (in_array($field
        ->getType(), $allowed_field_types) && !$field
        ->getFieldStorageDefinition()
        ->isBaseField()) {
        $options[$field_name] = $field
          ->getLabel();
      }
    }
    $form['source_field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Field with source information'),
      '#description' => $this
        ->t('Field on media entity that stores the media UUID from Bynder. You can create a bundle without selecting a value for this dropdown initially. This dropdown can be populated after adding fields to the bundle.'),
      '#default_value' => $this->configuration['source_field'] ?: NULL,
      '#options' => $options,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function getDefaultThumbnail() {
    return $this->config
      ->get('icon_base') . '/bynder_no_image.png';
  }

  /**
   * {@inheritdoc}
   */
  public function thumbnail(MediaInterface $media) {
    if ($thumbnail = $this
      ->getField($media, 'thumbnail_urls')) {
      if (isset($thumbnail['webimage'])) {
        if ($file = system_retrieve_file($thumbnail['webimage'], NULL, TRUE)) {
          return $file
            ->getFileUri();
        }
      }
    }
    return $this
      ->getDefaultThumbnail();
  }

  /**
   * {@inheritdoc}
   */
  public function getDefaultName(MediaInterface $media) {
    if ($name = $this
      ->getField($media, 'name')) {
      return $name;
    }
    return parent::getDefaultName($media);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
Bynder::$accountProxy protected property Account proxy.
Bynder::$apiResponse protected property Statically cached API response for a given asset.
Bynder::$bynderApi protected property Bynder api service.
Bynder::$cache protected property The cache service.
Bynder::$configFactory protected property The config factory.
Bynder::$logger protected property The logger factory service.
Bynder::$time protected property The time service.
Bynder::$timoutDetected protected static property Used to track if an API request returned a timout error.
Bynder::$urlGenerator protected property The url generator.
Bynder::buildConfigurationForm public function Form constructor. Overrides MediaTypeBase::buildConfigurationForm
Bynder::create public static function Creates an instance of the plugin. Overrides MediaTypeBase::create
Bynder::defaultConfiguration public function Gets default configuration for this plugin. Overrides MediaTypeBase::defaultConfiguration
Bynder::getDefaultName public function Provide a default name for the media. Overrides MediaTypeBase::getDefaultName
Bynder::getDefaultThumbnail public function Gets the default thumbnail image. Overrides MediaTypeBase::getDefaultThumbnail
Bynder::getField public function Gets a media-related field/value. Overrides MediaTypeInterface::getField
Bynder::providedFields public function Gets list of fields provided by this plugin. Overrides MediaTypeInterface::providedFields
Bynder::thumbnail public function Gets thumbnail image. Overrides MediaTypeInterface::thumbnail
Bynder::__construct public function Constructs a new class instance. Overrides MediaTypeBase::__construct
MediaTypeBase::$config protected property Media entity image config object.
MediaTypeBase::$entityFieldManager protected property The entity field manager service.
MediaTypeBase::$entityTypeManager protected property The entity type manager service.
MediaTypeBase::$label protected property Plugin label.
MediaTypeBase::attachConstraints public function Attaches type-specific constraints to media. Overrides MediaTypeInterface::attachConstraints
MediaTypeBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
MediaTypeBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurablePluginInterface::getConfiguration
MediaTypeBase::label public function Returns the display label. Overrides MediaTypeInterface::label
MediaTypeBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurablePluginInterface::setConfiguration
MediaTypeBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm
MediaTypeBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
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.