You are here

class Soundcloud in Media entity Soundcloud 8

Provides media type plugin for Soundcloud.

Plugin annotation


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

Hierarchy

Expanded class hierarchy of Soundcloud

1 file declares its use of Soundcloud
SoundcloudEmbedFormatter.php in src/Plugin/Field/FieldFormatter/SoundcloudEmbedFormatter.php
1 string reference to 'Soundcloud'
SoundcloudEmbedFormatterTest::testSoundcloudEmbedFormatter in src/Tests/SoundcloudEmbedFormatterTest.php
Tests adding and editing a soundcloud embed formatter.

File

src/Plugin/MediaEntity/Type/Soundcloud.php, line 23

Namespace

Drupal\media_entity_soundcloud\Plugin\MediaEntity\Type
View source
class Soundcloud extends MediaTypeBase {

  /**
   * @var array
   */
  protected $soundcloud;

  /**
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * @var \GuzzleHttp\ClientInterface
   */
  protected $httpClient;

  /**
   * @inheritDoc
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, ConfigFactoryInterface $configFactory, ClientInterface $httpClient) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $entity_field_manager, $configFactory
      ->get('media_entity.settings'));
    $this->configFactory = $configFactory;
    $this->httpClient = $httpClient;
  }

  /**
   * {@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('http_client'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = [];
    $options = [
      '' => $this
        ->t('Select'),
    ];
    $bundle = $form_state
      ->getFormObject()
      ->getEntity();
    $allowed_field_types = [
      'string',
      'string_long',
      'link',
    ];
    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();
      }
    }
    $disabled = !count($options);
    if ($disabled) {
      $options = [
        '' => $this
          ->t('Add fields to the media bundle'),
      ];
    }
    $form['source_url_field'] = [
      '#type' => 'select',
      '#title' => t('Soundcloud URL source field'),
      '#description' => t('Select the field on the media entity that stores Soundcloud URL.'),
      '#default_value' => isset($this->configuration['source_url_field']) ? $this->configuration['source_url_field'] : '',
      '#options' => $options,
      '#disabled' => $disabled,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function providedFields() {
    return [
      'track_id' => $this
        ->t('The track id'),
      'html' => $this
        ->t('HTML embed code'),
      'thumbnail_uri' => t('URI of the thumbnail'),
    ];
  }

  /**
   * @inheritDoc
   */
  public function getField(MediaInterface $media, $name) {
    if (($url = $this
      ->getMediaUrl($media)) && ($data = $this
      ->oEmbed($url))) {
      switch ($name) {
        case 'html':
          return $data['html'];
        case 'thumbnail_uri':
          if (isset($data['thumbnail_url'])) {
            $destination = $this->configFactory
              ->get('media_entity_soundcloud.settings')
              ->get('thumbnail_destination');
            $local_uri = $destination . '/' . pathinfo($data['thumbnail_url'], PATHINFO_BASENAME);

            // Save the file if it does not exist.
            if (!file_exists($local_uri)) {
              file_prepare_directory($destination, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
              $image = file_get_contents($data['thumbnail_url']);
              file_unmanaged_save_data($image, $local_uri, FILE_EXISTS_REPLACE);
              return $local_uri;
            }
          }
          return FALSE;
        case 'track_id':

          // Extract the src attribute from the html code.
          preg_match('/src="([^"]+)"/', $data['html'], $src_matches);
          if (!count($src_matches)) {
            return FALSE;
          }

          // Extract the id from the src.
          preg_match('/\\/tracks\\/(\\d*)/', urldecode($src_matches[1]), $matches);
          if (!count($matches)) {
            return FALSE;
          }
          return $matches[1];
      }
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function thumbnail(MediaInterface $media) {
    if ($thumbnail_image = $this
      ->getField($media, 'thumbnail_uri')) {
      return $thumbnail_image;
    }
    return $this
      ->getDefaultThumbnail();
  }

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

  /**
   * Returns the track id from the source_url_field.
   *
   * @param \Drupal\media_entity\MediaInterface $media
   *  The media entity.
   *
   * @return string|bool
   *  The track if from the source_url_field if found. False otherwise.
   */
  protected function getMediaUrl(MediaInterface $media) {
    if (isset($this->configuration['source_url_field'])) {
      $source_url_field = $this->configuration['source_url_field'];
      if ($media
        ->hasField($source_url_field)) {
        if (!empty($media->{$source_url_field}
          ->first())) {
          $property_name = $media->{$source_url_field}
            ->first()
            ->mainPropertyName();
          return $media->{$source_url_field}->{$property_name};
        }
      }
    }
    return FALSE;
  }

  /**
   * Returns oembed data for a Soundcloud url.
   *
   * @param string $url
   *   The Soundcloud Url.
   *
   * @return array
   *  An array of oembed data.
   */
  protected function oEmbed($url) {
    $this->soundcloud =& drupal_static(__FUNCTION__ . hash('md5', $url));
    if (!isset($this->soundcloud)) {
      $url = 'https://soundcloud.com/oembed?format=json&url=' . $url;
      $response = $this->httpClient
        ->get($url);
      $this->soundcloud = json_decode((string) $response
        ->getBody(), TRUE);
    }
    return $this->soundcloud;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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::getDefaultName public function Provide a default name for the media. Overrides MediaTypeInterface::getDefaultName
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.
Soundcloud::$configFactory protected property
Soundcloud::$httpClient protected property
Soundcloud::$soundcloud protected property
Soundcloud::buildConfigurationForm public function Form constructor. Overrides MediaTypeBase::buildConfigurationForm
Soundcloud::create public static function Creates an instance of the plugin. Overrides MediaTypeBase::create
Soundcloud::defaultConfiguration public function Gets default configuration for this plugin. Overrides MediaTypeBase::defaultConfiguration
Soundcloud::getDefaultThumbnail public function Gets the default thumbnail image. Overrides MediaTypeBase::getDefaultThumbnail
Soundcloud::getField public function @inheritDoc Overrides MediaTypeInterface::getField
Soundcloud::getMediaUrl protected function Returns the track id from the source_url_field.
Soundcloud::oEmbed protected function Returns oembed data for a Soundcloud url.
Soundcloud::providedFields public function Gets list of fields provided by this plugin. Overrides MediaTypeInterface::providedFields
Soundcloud::thumbnail public function Gets thumbnail image. Overrides MediaTypeInterface::thumbnail
Soundcloud::__construct public function @inheritDoc Overrides MediaTypeBase::__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.