Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / lib / Drupal / Core / Config / DatabaseStorage.php
1 <?php
2
3 namespace Drupal\Core\Config;
4
5 use Drupal\Core\Database\Database;
6 use Drupal\Core\Database\Connection;
7 use Drupal\Core\Database\SchemaObjectExistsException;
8 use Drupal\Core\DependencyInjection\DependencySerializationTrait;
9
10 /**
11  * Defines the Database storage.
12  */
13 class DatabaseStorage implements StorageInterface {
14   use DependencySerializationTrait;
15
16   /**
17    * The database connection.
18    *
19    * @var \Drupal\Core\Database\Connection
20    */
21   protected $connection;
22
23   /**
24    * The database table name.
25    *
26    * @var string
27    */
28   protected $table;
29
30   /**
31    * Additional database connection options to use in queries.
32    *
33    * @var array
34    */
35   protected $options = [];
36
37   /**
38    * The storage collection.
39    *
40    * @var string
41    */
42   protected $collection = StorageInterface::DEFAULT_COLLECTION;
43
44   /**
45    * Constructs a new DatabaseStorage.
46    *
47    * @param \Drupal\Core\Database\Connection $connection
48    *   A Database connection to use for reading and writing configuration data.
49    * @param string $table
50    *   A database table name to store configuration data in.
51    * @param array $options
52    *   (optional) Any additional database connection options to use in queries.
53    * @param string $collection
54    *   (optional) The collection to store configuration in. Defaults to the
55    *   default collection.
56    */
57   public function __construct(Connection $connection, $table, array $options = [], $collection = StorageInterface::DEFAULT_COLLECTION) {
58     $this->connection = $connection;
59     $this->table = $table;
60     $this->options = $options;
61     $this->collection = $collection;
62   }
63
64   /**
65    * {@inheritdoc}
66    */
67   public function exists($name) {
68     try {
69       return (bool) $this->connection->queryRange('SELECT 1 FROM {' . $this->connection->escapeTable($this->table) . '} WHERE collection = :collection AND name = :name', 0, 1, [
70         ':collection' => $this->collection,
71         ':name' => $name,
72       ], $this->options)->fetchField();
73     }
74     catch (\Exception $e) {
75       // If we attempt a read without actually having the database or the table
76       // available, just return FALSE so the caller can handle it.
77       return FALSE;
78     }
79   }
80
81   /**
82    * {@inheritdoc}
83    */
84   public function read($name) {
85     $data = FALSE;
86     try {
87       $raw = $this->connection->query('SELECT data FROM {' . $this->connection->escapeTable($this->table) . '} WHERE collection = :collection AND name = :name', [':collection' => $this->collection, ':name' => $name], $this->options)->fetchField();
88       if ($raw !== FALSE) {
89         $data = $this->decode($raw);
90       }
91     }
92     catch (\Exception $e) {
93       // If we attempt a read without actually having the database or the table
94       // available, just return FALSE so the caller can handle it.
95     }
96     return $data;
97   }
98
99   /**
100    * {@inheritdoc}
101    */
102   public function readMultiple(array $names) {
103     $list = [];
104     try {
105       $list = $this->connection->query('SELECT name, data FROM {' . $this->connection->escapeTable($this->table) . '} WHERE collection = :collection AND name IN ( :names[] )', [':collection' => $this->collection, ':names[]' => $names], $this->options)->fetchAllKeyed();
106       foreach ($list as &$data) {
107         $data = $this->decode($data);
108       }
109     }
110     catch (\Exception $e) {
111       // If we attempt a read without actually having the database or the table
112       // available, just return an empty array so the caller can handle it.
113     }
114     return $list;
115   }
116
117   /**
118    * {@inheritdoc}
119    */
120   public function write($name, array $data) {
121     $data = $this->encode($data);
122     try {
123       return $this->doWrite($name, $data);
124     }
125     catch (\Exception $e) {
126       // If there was an exception, try to create the table.
127       if ($this->ensureTableExists()) {
128         return $this->doWrite($name, $data);
129       }
130       // Some other failure that we can not recover from.
131       throw $e;
132     }
133   }
134
135   /**
136    * Helper method so we can re-try a write.
137    *
138    * @param string $name
139    *   The config name.
140    * @param string $data
141    *   The config data, already dumped to a string.
142    *
143    * @return bool
144    */
145   protected function doWrite($name, $data) {
146     $options = ['return' => Database::RETURN_AFFECTED] + $this->options;
147     return (bool) $this->connection->merge($this->table, $options)
148       ->keys(['collection', 'name'], [$this->collection, $name])
149       ->fields(['data' => $data])
150       ->execute();
151   }
152
153   /**
154    * Check if the config table exists and create it if not.
155    *
156    * @return bool
157    *   TRUE if the table was created, FALSE otherwise.
158    *
159    * @throws \Drupal\Core\Config\StorageException
160    *   If a database error occurs.
161    */
162   protected function ensureTableExists() {
163     try {
164       if (!$this->connection->schema()->tableExists($this->table)) {
165         $this->connection->schema()->createTable($this->table, static::schemaDefinition());
166         return TRUE;
167       }
168     }
169     // If another process has already created the config table, attempting to
170     // recreate it will throw an exception. In this case just catch the
171     // exception and do nothing.
172     catch (SchemaObjectExistsException $e) {
173       return TRUE;
174     }
175     catch (\Exception $e) {
176       throw new StorageException($e->getMessage(), NULL, $e);
177     }
178     return FALSE;
179   }
180
181   /**
182    * Defines the schema for the configuration table.
183    *
184    * @internal
185    */
186   protected static function schemaDefinition() {
187     $schema = [
188       'description' => 'The base table for configuration data.',
189       'fields' => [
190         'collection' => [
191           'description' => 'Primary Key: Config object collection.',
192           'type' => 'varchar_ascii',
193           'length' => 255,
194           'not null' => TRUE,
195           'default' => '',
196         ],
197         'name' => [
198           'description' => 'Primary Key: Config object name.',
199           'type' => 'varchar_ascii',
200           'length' => 255,
201           'not null' => TRUE,
202           'default' => '',
203         ],
204         'data' => [
205           'description' => 'A serialized configuration object data.',
206           'type' => 'blob',
207           'not null' => FALSE,
208           'size' => 'big',
209         ],
210       ],
211       'primary key' => ['collection', 'name'],
212     ];
213     return $schema;
214   }
215
216   /**
217    * Implements Drupal\Core\Config\StorageInterface::delete().
218    *
219    * @throws PDOException
220    *
221    * @todo Ignore replica targets for data manipulation operations.
222    */
223   public function delete($name) {
224     $options = ['return' => Database::RETURN_AFFECTED] + $this->options;
225     return (bool) $this->connection->delete($this->table, $options)
226       ->condition('collection', $this->collection)
227       ->condition('name', $name)
228       ->execute();
229   }
230
231   /**
232    * Implements Drupal\Core\Config\StorageInterface::rename().
233    *
234    * @throws PDOException
235    */
236   public function rename($name, $new_name) {
237     $options = ['return' => Database::RETURN_AFFECTED] + $this->options;
238     return (bool) $this->connection->update($this->table, $options)
239       ->fields(['name' => $new_name])
240       ->condition('name', $name)
241       ->condition('collection', $this->collection)
242       ->execute();
243   }
244
245   /**
246    * {@inheritdoc}
247    */
248   public function encode($data) {
249     return serialize($data);
250   }
251
252   /**
253    * Implements Drupal\Core\Config\StorageInterface::decode().
254    *
255    * @throws ErrorException
256    *   The unserialize() call will trigger E_NOTICE if the string cannot
257    *   be unserialized.
258    */
259   public function decode($raw) {
260     $data = @unserialize($raw);
261     return is_array($data) ? $data : FALSE;
262   }
263
264   /**
265    * {@inheritdoc}
266    */
267   public function listAll($prefix = '') {
268     try {
269       $query = $this->connection->select($this->table);
270       $query->fields($this->table, ['name']);
271       $query->condition('collection', $this->collection, '=');
272       $query->condition('name', $prefix . '%', 'LIKE');
273       $query->orderBy('collection')->orderBy('name');
274       return $query->execute()->fetchCol();
275     }
276     catch (\Exception $e) {
277       return [];
278     }
279   }
280
281   /**
282    * {@inheritdoc}
283    */
284   public function deleteAll($prefix = '') {
285     try {
286       $options = ['return' => Database::RETURN_AFFECTED] + $this->options;
287       return (bool) $this->connection->delete($this->table, $options)
288         ->condition('name', $prefix . '%', 'LIKE')
289         ->condition('collection', $this->collection)
290         ->execute();
291     }
292     catch (\Exception $e) {
293       return FALSE;
294     }
295   }
296
297   /**
298    * {@inheritdoc}
299    */
300   public function createCollection($collection) {
301     return new static(
302       $this->connection,
303       $this->table,
304       $this->options,
305       $collection
306     );
307   }
308
309   /**
310    * {@inheritdoc}
311    */
312   public function getCollectionName() {
313     return $this->collection;
314   }
315
316   /**
317    * {@inheritdoc}
318    */
319   public function getAllCollectionNames() {
320     try {
321       return $this->connection->query('SELECT DISTINCT collection FROM {' . $this->connection->escapeTable($this->table) . '} WHERE collection <> :collection ORDER by collection', [
322           ':collection' => StorageInterface::DEFAULT_COLLECTION,
323         ]
324       )->fetchCol();
325     }
326     catch (\Exception $e) {
327       return [];
328     }
329   }
330
331 }