aws_s3_stream_wrapper-1.0.x-dev/src/StreamWrapper/S3StreamWrapperPrefixedPathsTrait.php

src/StreamWrapper/S3StreamWrapperPrefixedPathsTrait.php
<?php

namespace Drupal\aws_s3_stream_wrapper\StreamWrapper;

/**
 * Provide a Drupal-based stream-wrapper against AWS S3 buckets.
 */
trait S3StreamWrapperPrefixedPathsTrait {

  /**
   * {@inheritdoc}
   */
  public function stream_open($path, $mode, $options, &$opened_path) {
    return parent::stream_open($this->getPrefixedPath($path), $mode, $options, $opened_path);
  }

  /**
   * {@inheritdoc}
   */
  public function unlink($path) {
    return parent::unlink($this->getPrefixedPath($path));
  }

  /**
   * {@inheritdoc}
   */
  public function url_stat($path, $flags) {
    return parent::url_stat($this->getPrefixedPath($path), $flags);
  }

  /**
   * {@inheritdoc}
   */
  public function mkdir($path, $mode, $options) {
    return parent::mkdir($this->getPrefixedPath($path), $mode, $options);
  }

  /**
   * {@inheritdoc}
   */
  public function rmdir($path, $options) {
    return parent::rmdir($this->getPrefixedPath($path), $options);
  }

  /**
   * {@inheritdoc}
   */
  public function dir_opendir($path, $options) {
    return parent::dir_opendir($this->getPrefixedPath($path), $options);
  }

  /**
   * {@inheritdoc}
   */
  public function rename($path_from, $path_to) {
    return parent::rename($this->getPrefixedPath($path_from), $this->getPrefixedPath($path_to));
  }

  /**
   * Get the path, applying the bucket name and optional path prefix.
   *
   * @param string $path
   *   The requested path.
   *
   * @return string
   *   The path, with the bucket and path prefix added.
   */
  private function getPrefixedPath($path) {
    $parts = explode('://', $path, 2);
    $protocol = $parts[0] ?: 's3';

    list ($bucket, $prefix) = $this->getPrefixConfiguration($protocol);
    if ($bucket && $prefix) {
      return "{$protocol}://{$bucket}/{$prefix}/" . $parts[1];
    }
    elseif ($bucket) {
      return "{$protocol}://{$bucket}/" . $parts[1];
    }
    return $path;
  }

  /**
   * Get the bucket and path prefix, if provided.
   *
   * @return array
   *   The name of the bucket to use, and an optional path prefix.
   */
  private function getPrefixConfiguration($protocol) {
    $streamOptions = stream_context_get_options(stream_context_get_default());
    $default = $streamOptions[$protocol] ?? NULL;
    if (!empty($default['s3BucketName'])) {
      return [
        $default['s3BucketName'],
        $default['s3BucketPathPrefix'] ?? '',
      ];
    }
    return ['', ''];
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc