SimpleStorage.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @package Grav\Framework\Flex
  5. *
  6. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  7. * @license MIT License; see LICENSE file for details.
  8. */
  9. namespace Grav\Framework\Flex\Storage;
  10. use Grav\Common\Filesystem\Folder;
  11. use InvalidArgumentException;
  12. /**
  13. * Class SimpleStorage
  14. * @package Grav\Framework\Flex\Storage
  15. */
  16. class SimpleStorage extends AbstractFilesystemStorage
  17. {
  18. /** @var string */
  19. protected $dataFolder;
  20. /** @var string */
  21. protected $dataPattern;
  22. /** @var array */
  23. protected $data;
  24. /**
  25. * {@inheritdoc}
  26. * @see FlexStorageInterface::__construct()
  27. */
  28. public function __construct(array $options)
  29. {
  30. if (!isset($options['folder'])) {
  31. throw new InvalidArgumentException("Argument \$options is missing 'folder'");
  32. }
  33. $formatter = $options['formatter'] ?? $this->detectDataFormatter($options['folder']);
  34. $this->initDataFormatter($formatter);
  35. $extension = $this->dataFormatter->getDefaultFileExtension();
  36. $pattern = basename($options['folder']);
  37. $this->dataPattern = basename($pattern, $extension) . $extension;
  38. $this->dataFolder = \dirname($options['folder']);
  39. // Make sure that the data folder exists.
  40. if (!file_exists($this->dataFolder)) {
  41. try {
  42. Folder::create($this->dataFolder);
  43. } catch (\RuntimeException $e) {
  44. throw new \RuntimeException(sprintf('Flex: %s', $e->getMessage()));
  45. }
  46. }
  47. }
  48. /**
  49. * {@inheritdoc}
  50. * @see FlexStorageInterface::getExistingKeys()
  51. */
  52. public function getExistingKeys(): array
  53. {
  54. return $this->buildIndex();
  55. }
  56. /**
  57. * {@inheritdoc}
  58. * @see FlexStorageInterface::hasKey()
  59. */
  60. public function hasKey(string $key): bool
  61. {
  62. if (null === $this->data) {
  63. $this->buildIndex();
  64. }
  65. return $key && strpos($key, '@@') === false && isset($this->data[$key]);
  66. }
  67. /**
  68. * {@inheritdoc}
  69. * @see FlexStorageInterface::createRows()
  70. */
  71. public function createRows(array $rows): array
  72. {
  73. if (null === $this->data) {
  74. $this->buildIndex();
  75. }
  76. $list = [];
  77. foreach ($rows as $key => $row) {
  78. $key = $this->getNewKey();
  79. $this->data[$key] = $list[$key] = $row;
  80. }
  81. if ($list) {
  82. $this->save();
  83. }
  84. return $list;
  85. }
  86. /**
  87. * {@inheritdoc}
  88. * @see FlexStorageInterface::readRows()
  89. */
  90. public function readRows(array $rows, array &$fetched = null): array
  91. {
  92. if (null === $this->data) {
  93. $this->buildIndex();
  94. }
  95. $list = [];
  96. foreach ($rows as $key => $row) {
  97. if (null === $row || (!\is_object($row) && !\is_array($row))) {
  98. // Only load rows which haven't been loaded before.
  99. $key = (string)$key;
  100. $list[$key] = $this->hasKey($key) ? $this->data[$key] : null;
  101. if (null !== $fetched) {
  102. $fetched[$key] = $list[$key];
  103. }
  104. } else {
  105. // Keep the row if it has been loaded.
  106. $list[$key] = $row;
  107. }
  108. }
  109. return $list;
  110. }
  111. /**
  112. * {@inheritdoc}
  113. * @see FlexStorageInterface::updateRows()
  114. */
  115. public function updateRows(array $rows): array
  116. {
  117. if (null === $this->data) {
  118. $this->buildIndex();
  119. }
  120. $list = [];
  121. foreach ($rows as $key => $row) {
  122. $key = (string)$key;
  123. if ($this->hasKey($key)) {
  124. $this->data[$key] = $list[$key] = $row;
  125. }
  126. }
  127. if ($list) {
  128. $this->save();
  129. }
  130. return $list;
  131. }
  132. /**
  133. * {@inheritdoc}
  134. * @see FlexStorageInterface::deleteRows()
  135. */
  136. public function deleteRows(array $rows): array
  137. {
  138. if (null === $this->data) {
  139. $this->buildIndex();
  140. }
  141. $list = [];
  142. foreach ($rows as $key => $row) {
  143. $key = (string)$key;
  144. if ($this->hasKey($key)) {
  145. unset($this->data[$key]);
  146. $list[$key] = $row;
  147. }
  148. }
  149. if ($list) {
  150. $this->save();
  151. }
  152. return $list;
  153. }
  154. /**
  155. * {@inheritdoc}
  156. * @see FlexStorageInterface::replaceRows()
  157. */
  158. public function replaceRows(array $rows): array
  159. {
  160. if (null === $this->data) {
  161. $this->buildIndex();
  162. }
  163. $list = [];
  164. foreach ($rows as $key => $row) {
  165. if (strpos($key, '@@')) {
  166. $key = $this->getNewKey();
  167. }
  168. $this->data[$key] = $list[$key] = $row;
  169. }
  170. if ($list) {
  171. $this->save();
  172. }
  173. return $list;
  174. }
  175. /**
  176. * {@inheritdoc}
  177. * @see FlexStorageInterface::renameRow()
  178. */
  179. public function renameRow(string $src, string $dst): bool
  180. {
  181. if (null === $this->data) {
  182. $this->buildIndex();
  183. }
  184. if ($this->hasKey($dst)) {
  185. throw new \RuntimeException("Cannot rename object: key '{$dst}' is already taken");
  186. }
  187. if (!$this->hasKey($src)) {
  188. return false;
  189. }
  190. // Change single key in the array without changing the order or value.
  191. $keys = array_keys($this->data);
  192. $keys[array_search($src, $keys, true)] = $dst;
  193. $data = array_combine($keys, $this->data);
  194. if (false === $data) {
  195. throw new \LogicException('Bad data');
  196. }
  197. $this->data = $data;
  198. return true;
  199. }
  200. /**
  201. * {@inheritdoc}
  202. * @see FlexStorageInterface::getStoragePath()
  203. */
  204. public function getStoragePath(string $key = null): string
  205. {
  206. return $this->dataFolder . '/' . $this->dataPattern;
  207. }
  208. /**
  209. * {@inheritdoc}
  210. * @see FlexStorageInterface::getMediaPath()
  211. */
  212. public function getMediaPath(string $key = null): string
  213. {
  214. return sprintf('%s/%s/%s', $this->dataFolder, basename($this->dataPattern, $this->dataFormatter->getDefaultFileExtension()), $key);
  215. }
  216. protected function save() : void
  217. {
  218. if (null === $this->data) {
  219. $this->buildIndex();
  220. }
  221. try {
  222. $file = $this->getFile($this->getStoragePath());
  223. $file->save($this->data);
  224. $file->free();
  225. } catch (\RuntimeException $e) {
  226. throw new \RuntimeException(sprintf('Flex save(): %s', $e->getMessage()));
  227. }
  228. }
  229. /**
  230. * Get key from the filesystem path.
  231. *
  232. * @param string $path
  233. * @return string
  234. */
  235. protected function getKeyFromPath(string $path): string
  236. {
  237. return basename($path);
  238. }
  239. /**
  240. * Returns list of all stored keys in [key => timestamp] pairs.
  241. *
  242. * @return array
  243. */
  244. protected function buildIndex(): array
  245. {
  246. $file = $this->getFile($this->getStoragePath());
  247. $modified = $file->modified();
  248. $this->data = (array) $file->content();
  249. $list = [];
  250. foreach ($this->data as $key => $info) {
  251. $list[$key] = [
  252. 'storage_key' => $key,
  253. 'storage_timestamp' => $modified
  254. ];
  255. }
  256. return $list;
  257. }
  258. /**
  259. * @return string
  260. */
  261. protected function getNewKey(): string
  262. {
  263. if (null === $this->data) {
  264. $this->buildIndex();
  265. }
  266. // Make sure that the key doesn't exist.
  267. do {
  268. $key = $this->generateKey();
  269. } while (isset($this->data[$key]));
  270. return $key;
  271. }
  272. }