You are here

class File in Freelinking 8.3

Same name and namespace in other branches
  1. 4.0.x src/Plugin/freelinking/File.php \Drupal\freelinking\Plugin\freelinking\File

Freelinking file plugin.

Plugin annotation


@Freelinking(
  id = "file",
  title = @Translation("File"),
  weight = 0,
  hidden = false,
  settings = {
    "scheme" = "public"
  }
)

Hierarchy

Expanded class hierarchy of File

1 file declares its use of File
FileTest.php in tests/src/Unit/Plugin/freelinking/FileTest.php
1 string reference to 'File'
FileTest::getPlugin in tests/src/Unit/Plugin/freelinking/FileTest.php
Get the plugin to test.

File

src/Plugin/freelinking/File.php, line 28

Namespace

Drupal\freelinking\Plugin\freelinking
View source
class File extends FreelinkingPluginBase implements ContainerFactoryPluginInterface {

  /**
   * File system configuration.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $fileSystemConfig;

  /**
   * Stream wrapper manager.
   *
   * @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface
   */
  protected $streamWrapperManager;

  /**
   * Module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * Initialize method.
   *
   * @param array $configuration
   *   The plugin configuration array.
   * @param string $plugin_id
   *   The plugin ID.
   * @param array $plugin_definition
   *   The plugin definition array.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   The configuration factory.
   * @param \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $streamWrapperManager
   *   The stream wrapper manager.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $moduleHandler
   *   The module handler.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $configFactory, StreamWrapperManagerInterface $streamWrapperManager, ModuleHandlerInterface $moduleHandler) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->fileSystemConfig = $configFactory
      ->get('system.file');
    $this->streamWrapperManager = $streamWrapperManager;
    $this->moduleHandler = $moduleHandler;
  }

  /**
   * {@inheritdoc}
   */
  public function getIndicator() {
    return '/^file$/i';
  }

  /**
   * {@inheritdoc}
   */
  public function getTip() {
    return $this
      ->t('Click to view a local file.');
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return parent::defaultConfiguration() + [
      'settings' => [
        'scheme' => $this->fileSystemConfig
          ->get('default_scheme'),
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element = [];
    $element['scheme'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('File System'),
      '#description' => $this
        ->t('Choose the file system to use to lookup files.'),
      '#options' => $this
        ->getSchemeOptions(),
    ];
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function buildLink(array $target) {
    $scheme = $this
      ->getConfiguration()['settings']['scheme'];

    // Remove slash if it's present at first character.
    $dest = preg_replace('/^\\//', '', $target['dest']);
    $path = $scheme . '://' . $dest;
    $stream_wrapper = $this
      ->loadScheme($scheme);
    $stream_wrapper
      ->setUri($path);

    // Make sure that the file exists on the given scheme.
    if (!$stream_wrapper
      ->realpath()) {
      return [
        '#theme' => 'freelink_error',
        '#plugin' => 'file',
        '#message' => $this
          ->t('File @name not found', [
          '@name' => basename($path),
        ]),
      ];
    }

    // Check file access.
    $headers = $this->moduleHandler
      ->invokeAll('file_download', [
      $path,
    ]);
    if (in_array(-1, $headers)) {
      return [
        '#theme' => 'freelink_error',
        '#plugin' => 'file',
        '#message' => $this
          ->t('File @name not found', [
          '@name' => basename($path),
        ]),
      ];
    }

    // Return a link to the file.
    $file_url = $stream_wrapper
      ->getExternalUrl();
    return [
      '#type' => 'link',
      '#title' => isset($target['text']) ? $target['text'] : basename($path),
      '#url' => Url::fromUri($file_url, [
        'absolute' => TRUE,
        'language' => $target['language'],
      ]),
      '#attributes' => [
        'title' => isset($target['tooltip']) ? $target['tooltip'] : $this
          ->getTip(),
      ],
    ];
  }

  /**
   * Get the stream managers keyed by name for the options list.
   *
   * @return array
   *   An array of options.
   */
  protected function getSchemeOptions() {
    $options = [];
    $schemes = $this->streamWrapperManager
      ->getNames(StreamWrapperInterface::WRITE_VISIBLE);
    foreach ($schemes as $scheme => $name) {
      $options[$scheme] = $name;
    }
    return $options;
  }

  /**
   * Load the stream wrapper for a given scheme.
   *
   * @param string $scheme
   *   The scheme to load.
   *
   * @return \Drupal\Core\StreamWrapper\StreamWrapperInterface
   *   The stream wrapper to use.
   */
  protected function loadScheme($scheme) {
    return $this->streamWrapperManager
      ->getViaScheme($scheme);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('config.factory'), $container
      ->get('stream_wrapper_manager'), $container
      ->get('module_handler'));
  }

}

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
File::$fileSystemConfig protected property File system configuration.
File::$moduleHandler protected property Module handler.
File::$streamWrapperManager protected property Stream wrapper manager.
File::buildLink public function Build a link with the plugin. Overrides FreelinkingPluginInterface::buildLink
File::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
File::defaultConfiguration public function Gets default configuration for this plugin. Overrides FreelinkingPluginBase::defaultConfiguration
File::getIndicator public function A regular expression string to indicate what to replace for this plugin. Overrides FreelinkingPluginInterface::getIndicator
File::getSchemeOptions protected function Get the stream managers keyed by name for the options list.
File::getTip public function Provides tips for this freelinking plugin. Overrides FreelinkingPluginInterface::getTip
File::loadScheme protected function Load the stream wrapper for a given scheme.
File::settingsForm public function Plugin configuration form. Overrides FreelinkingPluginBase::settingsForm
File::__construct public function Initialize method. Overrides PluginBase::__construct
FreelinkingPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
FreelinkingPluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration 1
FreelinkingPluginBase::getFailoverPluginId public function Get the failover plugin ID (if applicable). Overrides FreelinkingPluginInterface::getFailoverPluginId 1
FreelinkingPluginBase::isHidden public function Determine if the plugin is built-in (always on). Overrides FreelinkingPluginInterface::isHidden
FreelinkingPluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
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.
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.