FileStorage.php 9.08 KB
Newer Older
1 2
<?php

3 4 5 6 7
/**
 * @file
 * Definition of Drupal\Core\Config\FileStorage.
 */

8 9
namespace Drupal\Core\Config;

10 11
use Drupal\Component\Serialization\Yaml;
use Drupal\Component\Serialization\Exception\InvalidDataTypeException;
12
use Drupal\Component\Utility\String;
13

14
/**
15
 * Defines the file storage.
16
 */
17
class FileStorage implements StorageInterface {
18

19 20 21 22 23 24 25
  /**
   * The storage collection.
   *
   * @var string
   */
  protected $collection;

26
  /**
27
   * The filesystem path for configuration objects.
28
   *
29
   * @var string
30
   */
31
  protected $directory = '';
32 33

  /**
34
   * Constructs a new FileStorage.
35 36 37
   *
   * @param string $directory
   *   A directory path to use for reading and writing of configuration files.
38 39 40
   * @param string $collection
   *   (optional) The collection to store configuration in. Defaults to the
   *   default collection.
41
   */
42
  public function __construct($directory, $collection = StorageInterface::DEFAULT_COLLECTION) {
43
    $this->directory = $directory;
44
    $this->collection = $collection;
45 46 47
  }

  /**
48
   * Returns the path to the configuration file.
49
   *
50 51
   * @return string
   *   The path to the configuration file.
52
   */
53
  public function getFilePath($name) {
54
    return $this->getCollectionDirectory() . '/' . $name . '.' . static::getFileExtension();
55 56 57 58 59 60 61 62 63 64
  }

  /**
   * Returns the file extension used by the file storage for all configuration files.
   *
   * @return string
   *   The file extension.
   */
  public static function getFileExtension() {
    return 'yml';
65 66
  }

67 68 69 70
  /**
   * Check if the directory exists and create it if not.
   */
  protected function ensureStorage() {
71 72 73 74 75 76
    $dir = $this->getCollectionDirectory();
    $success = file_prepare_directory($dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
    // Only create .htaccess file in root directory.
    if ($dir == $this->directory) {
      $success = $success && file_save_htaccess($this->directory, TRUE, TRUE);
    }
77
    if (!$success) {
78
      throw new StorageException('Failed to create config directory ' . $dir);
79 80 81 82
    }
    return $this;
  }

83
  /**
84
   * Implements Drupal\Core\Config\StorageInterface::exists().
85
   */
86 87
  public function exists($name) {
    return file_exists($this->getFilePath($name));
88 89 90
  }

  /**
91
   * Implements Drupal\Core\Config\StorageInterface::read().
92
   *
93
   * @throws \Drupal\Core\Config\UnsupportedDataTypeConfigException
94
   */
95 96
  public function read($name) {
    if (!$this->exists($name)) {
97
      return FALSE;
98 99
    }
    $data = file_get_contents($this->getFilePath($name));
100 101 102 103 104 105 106 107 108
    try {
      $data = $this->decode($data);
    }
    catch (InvalidDataTypeException $e) {
      throw new UnsupportedDataTypeConfigException(String::format('Invalid data type in config @name: !message', array(
        '@name' => $name,
        '!message' => $e->getMessage(),
      )));
    }
109
    return $data;
110 111
  }

112 113 114 115 116 117 118 119 120 121 122 123 124
  /**
   * {@inheritdoc}
   */
  public function readMultiple(array $names) {
    $list = array();
    foreach ($names as $name) {
      if ($data = $this->read($name)) {
        $list[$name] = $data;
      }
    }
    return $list;
  }

125
  /**
126
   * {@inheritdoc}
127
   */
128
  public function write($name, array $data) {
129 130 131
    try {
      $data = $this->encode($data);
    }
132 133 134 135 136
    catch (InvalidDataTypeException $e) {
      throw new StorageException(String::format('Invalid data type in config @name: !message', array(
        '@name' => $name,
        '!message' => $e->getMessage(),
      )));
137 138
    }

139 140
    $target = $this->getFilePath($name);
    $status = @file_put_contents($target, $data);
141 142 143 144 145
    if ($status === FALSE) {
      // Try to make sure the directory exists and try witing again.
      $this->ensureStorage();
      $status = @file_put_contents($target, $data);
    }
146 147
    if ($status === FALSE) {
      throw new StorageException('Failed to write configuration file: ' . $this->getFilePath($name));
148
    }
149 150 151
    else {
      drupal_chmod($target);
    }
152
    return TRUE;
153 154 155
  }

  /**
156
   * Implements Drupal\Core\Config\StorageInterface::delete().
157
   */
158 159
  public function delete($name) {
    if (!$this->exists($name)) {
160 161 162
      $dir = $this->getCollectionDirectory();
      if (!file_exists($dir)) {
        throw new StorageException($dir . '/ not found.');
163 164 165 166
      }
      return FALSE;
    }
    return drupal_unlink($this->getFilePath($name));
167
  }
168

169
  /**
170
   * Implements Drupal\Core\Config\StorageInterface::rename().
171 172 173 174 175 176 177 178 179
   */
  public function rename($name, $new_name) {
    $status = @rename($this->getFilePath($name), $this->getFilePath($new_name));
    if ($status === FALSE) {
      throw new StorageException('Failed to rename configuration file from: ' . $this->getFilePath($name) . ' to: ' . $this->getFilePath($new_name));
    }
    return TRUE;
  }

180
  /**
181
   * Implements Drupal\Core\Config\StorageInterface::encode().
182
   */
183
  public function encode($data) {
184
    return Yaml::encode($data);
185 186 187
  }

  /**
188
   * Implements Drupal\Core\Config\StorageInterface::decode().
189
   */
190
  public function decode($raw) {
191
    $data = Yaml::decode($raw);
192 193 194
    // A simple string is valid YAML for any reason.
    if (!is_array($data)) {
      return FALSE;
195
    }
196
    return $data;
197 198 199
  }

  /**
200
   * Implements Drupal\Core\Config\StorageInterface::listAll().
201
   */
202 203 204
  public function listAll($prefix = '') {
    // glob() silently ignores the error of a non-existing search directory,
    // even with the GLOB_ERR flag.
205 206
    $dir = $this->getCollectionDirectory();
    if (!file_exists($dir)) {
207
      return array();
208
    }
209
    $extension = '.' . static::getFileExtension();
210
    // \GlobIterator on Windows requires an absolute path.
211
    $files = new \GlobIterator(realpath($dir) . '/' . $prefix . '*' . $extension);
212 213 214 215 216 217 218

    $names = array();
    foreach ($files as $file) {
      $names[] = $file->getBasename($extension);
    }

    return $names;
219
  }
220 221 222 223 224 225 226 227 228 229 230 231

  /**
   * Implements Drupal\Core\Config\StorageInterface::deleteAll().
   */
  public function deleteAll($prefix = '') {
    $success = TRUE;
    $files = $this->listAll($prefix);
    foreach ($files as $name) {
      if (!$this->delete($name) && $success) {
        $success = FALSE;
      }
    }
232 233 234 235 236 237
    if ($success && $this->collection != StorageInterface::DEFAULT_COLLECTION) {
      // Remove empty directories.
      if (!(new \FilesystemIterator($this->getCollectionDirectory()))->valid()) {
        drupal_rmdir($this->getCollectionDirectory());
      }
    }
238 239
    return $success;
  }
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337

  /**
   * {@inheritdoc}
   */
  public function createCollection($collection) {
    return new static(
      $this->directory,
      $collection
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getCollectionName() {
    return $this->collection;
  }

  /**
   * {@inheritdoc}
   */
  public function getAllCollectionNames() {
    $collections = $this->getAllCollectionNamesHelper($this->directory);
    sort($collections);
    return $collections;
  }

  /**
   * Helper function for getAllCollectionNames().
   *
   * If the file storage has the following subdirectory structure:
   *   ./another_collection/one
   *   ./another_collection/two
   *   ./collection/sub/one
   *   ./collection/sub/two
   * this function will return:
   * @code
   *   array(
   *     'another_collection.one',
   *     'another_collection.two',
   *     'collection.sub.one',
   *     'collection.sub.two',
   *   );
   * @endcode
   *
   * @param string $directory
   *   The directory to check for sub directories. This allows this
   *   function to be used recursively to discover all the collections in the
   *   storage.
   *
   * @return array
   *   A list of collection names contained within the provided directory.
   */
  protected function getAllCollectionNamesHelper($directory) {
    $collections = array();
    foreach (new \DirectoryIterator($directory) as $fileinfo) {
      if ($fileinfo->isDir() && !$fileinfo->isDot()) {
        $collection = $fileinfo->getFilename();
        // Recursively call getAllCollectionNamesHelper() to discover if there
        // are subdirectories. Subdirectories represent a dotted collection
        // name.
        $sub_collections = $this->getAllCollectionNamesHelper($directory . '/' . $collection);
        if (!empty($sub_collections)) {
          // Build up the collection name by concatenating the subdirectory
          // names with the current directory name.
          foreach ($sub_collections as $sub_collection) {
            $collections[] = $collection . '.' . $sub_collection;
          }
        }
        // Check that the collection is valid by searching if for configuration
        // objects. A directory without any configuration objects is not a valid
        // collection.
        // \GlobIterator on Windows requires an absolute path.
        $files = new \GlobIterator(realpath($directory . '/' . $collection) . '/*.' . $this->getFileExtension());
        if (count($files)) {
          $collections[] = $collection;
        }
      }
    }
    return $collections;
  }

  /**
   * Gets the directory for the collection.
   *
   * @return string
   *   The directory for the collection.
   */
  protected function getCollectionDirectory() {
    if ($this->collection == StorageInterface::DEFAULT_COLLECTION) {
      $dir = $this->directory;
    }
    else {
      $dir = $this->directory . '/' . str_replace('.', '/', $this->collection);
    }
    return $dir;
  }

338
}