You are here

class SoundCloudDefaultFormatter in SoundCloud field 8

Plugin implementation of the 'soundcloud_default' formatter.

Plugin annotation


@FieldFormatter(
  id = "soundcloud_default",
  module = "soundcloudfield",
  label = @Translation("Default (HTML5 player)"),
  field_types = {
    "soundcloud"
  }
)

Hierarchy

Expanded class hierarchy of SoundCloudDefaultFormatter

File

src/Plugin/Field/FieldFormatter/SoundCloudDefaultFormatter.php, line 22

Namespace

Drupal\soundcloudfield\Plugin\Field\FieldFormatter
View source
class SoundCloudDefaultFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
      'soundcloud_player_type' => 'classic',
      'soundcloud_player_width' => SOUNDCLOUDFIELD_DEFAULT_WIDTH,
      'soundcloud_player_height' => SOUNDCLOUDFIELD_DEFAULT_HTML5_PLAYER_HEIGHT,
      'soundcloud_player_height_sets' => SOUNDCLOUDFIELD_DEFAULT_HTML5_PLAYER_HEIGHT_SETS,
      'soundcloud_player_visual_height' => SOUNDCLOUDFIELD_DEFAULT_VISUAL_PLAYER_HEIGHT,
      'soundcloud_player_autoplay' => '',
      'soundcloud_player_color' => 'ff7700',
      'soundcloud_player_hiderelated' => '',
      'soundcloud_player_showartwork' => '',
      'soundcloud_player_showcomments' => TRUE,
      'soundcloud_player_showplaycount' => '',
    ) + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $elements = parent::settingsForm($form, $form_state);
    $elements['soundcloud_player_type'] = array(
      '#title' => $this
        ->t('HTML5 player type'),
      '#description' => $this
        ->t('Select which HTML5 player to use.'),
      '#type' => 'select',
      '#default_value' => $this
        ->getSetting('soundcloud_player_type'),
      '#options' => array(
        'classic' => 'Classic',
        'visual' => 'Visual Player (new)',
      ),
    );
    $elements['soundcloud_player_width'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Width'),
      '#size' => 4,
      '#default_value' => $this
        ->getSetting('soundcloud_player_width'),
      '#description' => $this
        ->t('Player width in percent. Default is @width.', array(
        '@width' => SOUNDCLOUDFIELD_DEFAULT_WIDTH,
      )),
    );
    $elements['soundcloud_player_height'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Height'),
      '#size' => 4,
      '#default_value' => $this
        ->getSetting('soundcloud_player_height'),
      '#states' => array(
        'visible' => array(
          ':input[name*="soundcloud_player_type"]' => array(
            'value' => 'classic',
          ),
        ),
      ),
    );
    $elements['soundcloud_player_height_sets'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Height for sets'),
      '#size' => 4,
      '#default_value' => $this
        ->getSetting('soundcloud_player_height_sets'),
      '#states' => array(
        'visible' => array(
          ':input[name*="soundcloud_player_type"]' => array(
            'value' => 'classic',
          ),
        ),
      ),
    );
    $elements['soundcloud_player_visual_height'] = array(
      '#type' => 'select',
      '#title' => $this
        ->t('Height of the visual player'),
      '#size' => 4,
      '#default_value' => $this
        ->getSetting('soundcloud_player_visual_height'),
      '#options' => array(
        300 => '300px',
        450 => '450px',
        600 => '600px',
      ),
      '#states' => array(
        'visible' => array(
          ':input[name*="soundcloud_player_type"]' => array(
            'value' => 'visual',
          ),
        ),
      ),
    );
    $elements['soundcloud_player_autoplay'] = array(
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Play audio automatically when loaded (autoplay).'),
      '#default_value' => $this
        ->getSetting('soundcloud_player_autoplay'),
    );
    $elements['soundcloud_player_color'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Player color.'),
      '#default_value' => $this
        ->getSetting('soundcloud_player_color'),
      '#description' => $this
        ->t('Player color in hexadecimal format. Default is ff7700. Turn on the jQuery Colorpicker module if available.'),
    );
    $elements['soundcloud_player_hiderelated'] = array(
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Hide related tracks.'),
      '#default_value' => $this
        ->getSetting('soundcloud_player_hiderelated'),
    );
    $elements['soundcloud_player_showartwork'] = array(
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show artwork.'),
      '#default_value' => $this
        ->getSetting('soundcloud_player_showartwork'),
    );
    $elements['soundcloud_player_showcomments'] = array(
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show comments.'),
      '#default_value' => $this
        ->getSetting('soundcloud_player_showcomments'),
    );
    $elements['soundcloud_player_showplaycount'] = array(
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show play count.'),
      '#default_value' => $this
        ->getSetting('soundcloud_player_showplaycount'),
    );
    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = array();
    $settings = $this
      ->getSettings();
    $summary[] = $this
      ->t('Displays the SoundCloud player.');
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = array();
    $settings = $this
      ->getSettings();

    // Get the "common" settings.
    $width = $this
      ->getSetting('soundcloud_player_width');
    $autoplay = $this
      ->getSetting('soundcloud_player_autoplay') ? 'true' : 'false';
    $showcomments = $this
      ->getSetting('soundcloud_player_showcomments') ? 'true' : 'false';
    $showplaycount = $this
      ->getSetting('soundcloud_player_showplaycount') ? 'true' : 'false';
    $showartwork = $this
      ->getSetting('soundcloud_player_showartwork') ? 'true' : 'false';
    $color = $this
      ->getSetting('soundcloud_player_color') ? $this
      ->getSetting('soundcloud_player_color') : 'ff7700';

    //
    $oembed_endpoint = 'https://soundcloud.com/oembed';

    // Get 'HTML5 player'-specific settings.
    $html5_player_height = empty($settings['html5_player']['html5_player_height']) ? SOUNDCLOUDFIELD_DEFAULT_HTML5_PLAYER_HEIGHT : $settings['html5_player']['html5_player_height'];
    $html5_player_height_sets = empty($settings['html5_player']['html5_player_height_sets']) ? SOUNDCLOUDFIELD_DEFAULT_HTML5_PLAYER_HEIGHT_SETS : $settings['html5_player']['html5_player_height_sets'];
    $visual_player = $this
      ->getSetting('soundcloud_player_type') == 'visual' ? 'true' : 'false';
    foreach ($items as $delta => $item) {
      $output = '';
      $encoded_url = urlencode($item->url);

      // Set the proper height for this item.
      // - classic player: track default is 166px, set default is 450px.
      // - visual player: player height it's the same for tracks and sets.
      if ($visual_player == 'true') {
        $iframe_height = $settings['soundcloud_player_visual_height'];
      }
      else {
        $parsed_url = parse_url($item->url);
        $splitted_url = explode("/", $parsed_url['path']);

        // An artist page or a set or a track?
        $iframe_height = !isset($splitted_url[2]) || $splitted_url[2] == 'sets' ? $html5_player_height_sets : $html5_player_height;
      }

      // Create the URL.
      $oembed_url = $oembed_endpoint . '?iframe=true&format=json&url=' . $encoded_url;

      // curl get.
      $soundcloud_curl_get = _soundcloudfield_curl_get($oembed_url);
      if ($soundcloud_curl_get != ' ') {

        // Load in the oEmbed XML.
        $oembed = Json::decode($soundcloud_curl_get);

        // Replace player default settings with our settings,
        // set player width and height first.
        $final_iframe = preg_replace('/(width=)"([^"]+)"/', 'width="' . $width . '%"', $oembed['html']);
        $final_iframe = preg_replace('/(height=)"([^"]+)"/', 'height="' . $iframe_height . '"', $oembed['html']);

        // Set autoplay.
        if (preg_match('/auto_play=(true|false)/', $final_iframe)) {
          $final_iframe = preg_replace('/auto_play=(true|false)/', 'auto_play=' . $autoplay, $final_iframe);
        }
        else {
          $final_iframe = preg_replace('/">/', '&auto_play=' . $autoplay . '">', $final_iframe);
        }

        // Show comments?
        if (preg_match('/show_comments=(true|false)/', $final_iframe)) {
          $final_iframe = preg_replace('/show_comments=(true|false)/', 'show_comments=' . $showcomments, $final_iframe);
        }
        else {
          $final_iframe = preg_replace('/">/', '&show_comments=' . $showcomments . '">', $final_iframe);
        }

        // Show playcount?
        if (preg_match('/show_playcount=(true|false)/', $final_iframe)) {
          $final_iframe = preg_replace('/show_playcount=(true|false)/', 'show_playcount=' . $showplaycount, $final_iframe);
        }
        else {
          $final_iframe = preg_replace('/">/', '&show_playcount=' . $showplaycount . '">', $final_iframe);
        }

        // Show artwork?
        if (preg_match('/show_artwork=(true|false)/', $final_iframe)) {
          $final_iframe = preg_replace('/show_artwork=(true|false)/', 'show_artwork=' . $showartwork, $final_iframe);
        }
        else {
          $final_iframe = preg_replace('/">/', '&show_artwork=' . $showartwork . '">', $final_iframe);
        }

        // Set player color.
        if (preg_match('/color=([a-zA-Z0-9]{6})/', $final_iframe)) {
          $final_iframe = preg_replace('/color=([a-zA-Z0-9]{6})/', 'color=' . $color, $final_iframe);
        }
        else {
          $final_iframe = preg_replace('/">/', '&color=' . $color . '">', $final_iframe);
        }

        // Set HTML5 player type based on formatter: classic/visual player.
        if (preg_match('/visual=(true|false)/', $final_iframe)) {
          $final_iframe = preg_replace('/visual=(true|false)/', 'visual=' . $visual_player, $final_iframe);
        }
        else {
          $final_iframe = preg_replace('/">/', '&visual=' . $visual_player . '">', $final_iframe);
        }

        // Final output. Use '$oembed->html' for original embed code.
        $output = html_entity_decode($final_iframe);
      }
      else {
        $output = $this
          ->t('The SoundCloud content at <a href=":url">:url</a> is not available, or it is set to private.', [
          ':url' => $item->url,
        ]);
      }

      // Extract field item attributes for the theme function, and unset them
      // from the $item so that the field template does not re-render them.
      $item_attributes = $item->_attributes;
      unset($item->_attributes);

      // Render each element as markup.
      $elements[$delta] = array(
        '#markup' => $output,
        '#allowed_tags' => [
          'iframe',
        ],
      );

      //      $elements[$delta] = array(
      //        '#markup' => $item->value,
      //        '#markup' => $item->processed,
      //      );
    }
    return $elements;
  }
  protected function renderEmbedCode($track_id, $width, $height, $autoplay) {
    return [
      '#type' => 'html_tag',
      '#tag' => 'iframe',
      '#attributes' => [
        'width' => $width,
        'height' => $height,
        'frameborder' => '0',
        'allowfullscreen' => 'allowfullscreen',
        'src' => sprintf('https://w.soundcloud.com/player/%s?autoplay=%s', $track_id, $autoplay),
      ],
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
FormatterBase::$fieldDefinition protected property The field definition.
FormatterBase::$label protected property The label display setting.
FormatterBase::$settings protected property The formatter settings. Overrides PluginSettingsBase::$settings
FormatterBase::$viewMode protected property The view mode.
FormatterBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 11
FormatterBase::getFieldSetting protected function Returns the value of a field setting.
FormatterBase::getFieldSettings protected function Returns the array of field settings.
FormatterBase::isApplicable public static function Returns if the formatter can be used for the provided field. Overrides FormatterInterface::isApplicable 14
FormatterBase::prepareView public function Allows formatters to load information for field values being displayed. Overrides FormatterInterface::prepareView 2
FormatterBase::view public function Builds a renderable array for a fully themed field. Overrides FormatterInterface::view 1
FormatterBase::__construct public function Constructs a FormatterBase object. Overrides PluginBase::__construct 11
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
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.
PluginSettingsBase::$defaultSettingsMerged protected property Whether default settings have been merged into the current $settings.
PluginSettingsBase::$thirdPartySettings protected property The plugin settings injected by third party modules.
PluginSettingsBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 6
PluginSettingsBase::getSetting public function Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface::getSetting
PluginSettingsBase::getSettings public function Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface::getSettings
PluginSettingsBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
PluginSettingsBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
PluginSettingsBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
PluginSettingsBase::mergeDefaults protected function Merges default settings values into $settings.
PluginSettingsBase::onDependencyRemoval public function Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsInterface::onDependencyRemoval 3
PluginSettingsBase::setSetting public function Sets the value of a setting for the plugin. Overrides PluginSettingsInterface::setSetting
PluginSettingsBase::setSettings public function Sets the settings for the plugin. Overrides PluginSettingsInterface::setSettings
PluginSettingsBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
PluginSettingsBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
SoundCloudDefaultFormatter::defaultSettings public static function Defines the default settings for this plugin. Overrides PluginSettingsBase::defaultSettings
SoundCloudDefaultFormatter::renderEmbedCode protected function
SoundCloudDefaultFormatter::settingsForm public function Returns a form to configure settings for the formatter. Overrides FormatterBase::settingsForm
SoundCloudDefaultFormatter::settingsSummary public function Returns a short summary for the current formatter settings. Overrides FormatterBase::settingsSummary
SoundCloudDefaultFormatter::viewElements public function Builds a renderable array for a field value. Overrides FormatterInterface::viewElements
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.