summaryrefslogtreecommitdiffstats
path: root/src/ConfigSnapshotStorage.php
blob: 15851851d6953dfe3cbe5ec98d624cd34d4eda87 (plain)
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
35
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
71
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
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
338
339
340
341
342
343
344
345
346
347
348
349
350
<?php

namespace Drupal\config_snapshot;

use Drupal\config_snapshot\Entity\ConfigSnapshot;
use Drupal\Core\Config\StorageInterface;
use Symfony\Component\Yaml\Inline;

/**
 * Provides a configuration storage saved as simple configuration.
 */
class ConfigSnapshotStorage implements NormalizableStorageInterface {

  /**
   * The snapshot set.
   *
   * A set is a group of snapshots used for a particular purpose. A set should
   * be namespaced for the module introducing it.
   *
   * @var string
   */
  protected $snapshotSet;

  /**
   * The extension type.
   *
   * @var string
   */
  protected $extensionType;

  /**
   * The extension name.
   *
   * @var string
   */
  protected $extensionName;

  /**
   * The storage collection.
   *
   * @var string
   */
  protected $collection;

  /**
   * The configuration snapshot.
   *
   * @var \Drupal\config_snapshot\Entity\ConfigSnapshot
   */
  protected $configSnapshot;

  /**
   * Whether configuration should be normalized on read.
   *
   * @var bool
   */
  protected $normalizeOnRead;

  /**
   * Constructs a new ConfigSnapshotStorage.
   *
   * @param string $snapshot_set
   *   The snapshot set.
   * @param string $extension_type
   *   The extension type.
   * @param string $extension_name
   *   The extension name.
   * @param string $collection
   *   (optional) The collection to store configuration in. Defaults to the
   *   default collection.
   * @param \Drupal\config_snapshot\Entity\ConfigSnapshot $config_snapshot
   *   (optional) The configuration snapshot.
   * @param bool $normalize_on_read
   *   (optional) Whether data should be normalized on read. Defaults to FALSE.
   */
  public function __construct($snapshot_set, $extension_type, $extension_name, $collection = StorageInterface::DEFAULT_COLLECTION, ConfigSnapshot $config_snapshot = NULL, $normalize_on_read = FALSE) {
    $this->snapshotSet = $snapshot_set;
    $this->extensionType = $extension_type;
    $this->extensionName = $extension_name;
    $this->collection = $collection;
    $this->normalizeOnRead = $normalize_on_read;
    $this->setConfigSnapshot($config_snapshot);
  }

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

  /**
   * {@inheritdoc}
   */
  public function setNormalizeOnRead($normalize_on_read) {
    $this->normalizeOnRead = $normalize_on_read;
  }

  /**
   * Sets the config snapshot object associated with an extension.
   *
   * The function reads the config_snapshot object from the current
   * configuration, or returns a ready-to-use empty one if no configuration
   * entry exists yet for the extension.
   */
  protected function setConfigSnapshot($config_snapshot) {
    if (is_null($config_snapshot)) {
      // Try loading the snapshot from configuration.
      $config_snapshot = ConfigSnapshot::load("{$this->snapshotSet}.{$this->extensionType}.{$this->extensionName}");

      // If not found, create a fresh snapshot object.
      if (!$config_snapshot) {
        $config_snapshot = ConfigSnapshot::create([
          'snapshotSet' => $this->snapshotSet,
          'extensionType' => $this->extensionType,
          'extensionName' => $this->extensionName,
        ]);
      }
    }

    $this->configSnapshot = $config_snapshot;
  }

  /**
   * {@inheritdoc}
   */
  public function exists($name) {
    return !is_null($this->configSnapshot->getItem($this->collection, $name));
  }

  /**
   * {@inheritdoc}
   */
  public function read($name) {
    if ($item = $this->configSnapshot->getItem($this->collection, $name)) {
      $data = $item['data'];
      if ($this->normalizeOnRead) {
        $data = $this->normalizeArray($data);
      }

      return $data;
    }

    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function readMultiple(array $names) {
    $data = [];
    foreach ($names as $name) {
      $data[$name] = $this->read($name);
    }

    return $data;
  }

  /**
   * {@inheritdoc}
   */
  public function write($name, array $data) {
    $this->configSnapshot
      ->setItem($this->collection, $name, $data)
      ->save();

    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function delete($name) {
    if (!$this->exists($name)) {
      return FALSE;
    }
    $this->configSnapshot
      ->clearItem($this->collection, $name)
      ->save();

    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function rename($name, $new_name) {
    if (!$this->exists($name)) {
      return FALSE;
    }
    $this->write($new_name, $this->read($name));

    return $this->delete($name);
  }

  /**
   * {@inheritdoc}
   */
  public function encode($data) {
    return $data;
  }

  /**
   * {@inheritdoc}
   */
  public function decode($raw) {
    return $raw;
  }

  /**
   * {@inheritdoc}
   */
  public function listAll($prefix = '') {
    $names = [];
    $items = $this->configSnapshot->getItems();

    // Find the keys of the items in the current collection.
    $collection_keys = array_keys(array_column($items, 'collection'), $this->collection);

    if ($prefix === '') {
      $name_items = array_column($items, 'name');
      // Find all names in the current collection.
      $names = array_values(array_intersect_key($name_items, array_flip($collection_keys)));
    }
    else {
      foreach ($collection_keys as $key) {
        if (strpos($items[$key]['name'], $prefix) === 0) {
          $names[] = $items[$key]['name'];
        }
      }
    }

    return $names;
  }

  /**
   * {@inheritdoc}
   */
  public function deleteAll($prefix = '') {
    $items = $this->configSnapshot->getItems();
    $collection = $this->collection;
    $collection_items = array_filter($items, function ($item) use ($collection) {
      return ($item['collection'] === $collection);
    });
    if ($prefix === '') {
      $items = array_diff_key($items, $collection_items);
    }
    else {
      foreach (array_keys($collection_items) as $key) {
        if (strpos($items[$key]['name'], $prefix) === 0) {
          unset($items[$key]);
        }
      }
    }
    $this->configSnapshot
      ->setItems($items)
      ->save();

    return TRUE;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getAllCollectionNames() {
    $items = $this->configSnapshot->getItems();
    $collections = array_unique(array_column($items, 'collection'));
    // The default collection is not included here.
    unset($collections[array_search(StorageInterface::DEFAULT_COLLECTION, $collections)]);

    return array_values($collections);
  }

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

  /**
   * Writes configuration data to the storage for a collection.
   *
   * @param string $name
   *   The name of a configuration object to save.
   * @param array $data
   *   The configuration data to write.
   * @param string $collection
   *   The collection to store configuration in.
   *
   * @return bool
   *   TRUE on success, FALSE in case of an error.
   */
  public function writeToCollection($name, array $data, $collection) {
    $this->configSnapshot
      ->setItem($collection, $name, $data)
      ->save();

    return TRUE;
  }

  /**
   * Recursively sorts an array by key, and removes empty arrays.
   *
   * @param array $array
   *   An array to normalize.
   *
   * @return array
   *   An array that is sorted by key, at each level of the array, with empty
   *   arrays removed.
   *
   * @todo Replace this when
   *   https://www.drupal.org/project/config_update/issues/2989991 lands.
   */
  protected function normalizeArray(array $array) {
    foreach ($array as $key => $value) {
      if (is_array($value)) {
        $new = $this->normalizeArray($value);
        if (count($new)) {
          $array[$key] = $new;
        }
      }
    }

    // If the array is associative, sort by key.
    if (Inline::isHash($array)) {
      ksort($array);
    }
    // Otherwise, sort by value.
    else {
      sort($array);
    }

    return $array;
  }

}