PublicStream.php 2.61 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\Core\StreamWrapper\PublicStream.
6 7 8 9
 */

namespace Drupal\Core\StreamWrapper;

10
use Drupal\Component\Utility\UrlHelper;
11
use Drupal\Core\DrupalKernel;
12
use Drupal\Core\Site\Settings;
13
use Symfony\Component\HttpFoundation\Request;
14

15 16 17 18 19 20 21 22
/**
 * Defines a Drupal public (public://) stream wrapper class.
 *
 * Provides support for storing publicly accessible files with the Drupal file
 * interface.
 */
class PublicStream extends LocalStream {

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
  /**
   * {@inheritdoc}
   */
  public static function getType() {
    return StreamWrapperInterface::LOCAL_NORMAL;
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return t('Public files');
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    return t('Public local files served by the webserver.');
  }

44
  /**
45
   * {@inheritdoc}
46 47
   */
  public function getDirectoryPath() {
48
    return static::basePath();
49 50 51
  }

  /**
52
   * {@inheritdoc}
53
   */
54
  public function getExternalUrl() {
55
    $path = str_replace('\\', '/', $this->getTarget());
56
    return $GLOBALS['base_url'] . '/' . self::getDirectoryPath() . '/' . UrlHelper::encodePath($path);
57
  }
58 59 60 61

  /**
   * Returns the base path for public://.
   *
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
   * If we have a setting for the public:// scheme's path, we use that.
   * Otherwise we build a reasonable default based on the site.path service if
   * it's available, or a default behavior based on the request.
   *
   * The site path is injectable from the site.path service:
   * @code
   * $base_path = PublicStream::basePath(\Drupal::service('site.path'));
   * @endcode
   *
   * @param \SplString $site_path
   *   (optional) The site.path service parameter, which is typically the path
   *   to sites/ in a Drupal installation. This allows you to inject the site
   *   path using services from the caller. If omitted, this method will use the
   *   global service container or the kernel's default behavior to determine
   *   the site path.
   *
78 79 80
   * @return string
   *   The base path for public:// typically sites/default/files.
   */
81 82 83 84 85 86 87 88 89 90 91 92 93 94
  public static function basePath(\SplString $site_path = NULL) {
    if ($site_path === NULL) {
      // Find the site path. Kernel service is not always available at this
      // point, but is preferred, when available.
      if (\Drupal::hasService('kernel')) {
        $site_path = \Drupal::service('site.path');
      }
      else {
        // If there is no kernel available yet, we call the static
        // findSitePath().
        $site_path = DrupalKernel::findSitePath(Request::createFromGlobals());
      }
    }
    return Settings::get('file_public_path', $site_path . '/files');
95 96
  }

97
}