FileStorage.php 1.89 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
<?php

namespace Drupal\Core\Config;

/**
 * Represents the file storage interface.
 *
 * Classes implementing this interface allow reading and writing configuration
 * data to and from disk.
 */
class FileStorage {

  /**
   * Constructs a FileStorage object.
   *
   * @param string $name
   *   The name for the configuration data. Should be lowercase.
   */
  public function __construct($name) {
    $this->name = $name;
  }

  /**
   * Reads and returns a file.
   *
   * @return
   *   The data of the file.
   *
   * @throws
   *   Exception
   */
  protected function readData() {
    $data = file_get_contents($this->getFilePath());
    if ($data === FALSE) {
35
      throw new FileStorageReadException('Read file is invalid.');
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    }
    return $data;
  }

  /**
   * Checks whether the XML configuration file already exists on disk.
   *
   * @return
   *   @todo
   */
  protected function exists() {
    return file_exists($this->getFilePath());
  }

  /**
   * Returns the path to the XML configuration file.
   *
   * @return
   *   @todo
   */
  public function getFilePath() {
    return config_get_config_directory() . '/' . $this->name  . '.xml';
  }

  /**
   * Writes the contents of the configuration file to disk.
   *
   * @param $data
   *   The data to be written to the file.
   *
   * @throws
   *   Exception
   */
  public function write($data) {
    if (!file_put_contents($this->getFilePath(), $data)) {
71
      throw new FileStorageException('Failed to write configuration file: ' . $this->getFilePath());
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
    }
  }

  /**
   * Returns the contents of the configuration file.
   *
   * @return
   *   @todo
   */
  public function read() {
    if ($this->exists()) {
      $data = $this->readData();
      return $data;
    }
    return FALSE;
  }

  /**
   * Deletes a configuration file.
   */
  public function delete() {
    // Needs error handling and etc.
    @drupal_unlink($this->getFilePath());
  }
}