/web/core/lib/Drupal/Core/Config/DatabaseStorage.php

https://gitlab.com/mohamed_hussein/prodt · PHP · 328 lines · 183 code · 25 blank · 120 comment · 2 complexity · 4f5c5b01f7ae9fcd1cc0018e4bd7e10c MD5 · raw file

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