StorageFactory.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Files\Storage;
  8. use OCP\Files\Mount\IMountPoint;
  9. use OCP\Files\Storage\IConstructableStorage;
  10. use OCP\Files\Storage\IStorage;
  11. use OCP\Files\Storage\IStorageFactory;
  12. use Psr\Log\LoggerInterface;
  13. class StorageFactory implements IStorageFactory {
  14. /**
  15. * @var array[] [$name=>['priority'=>$priority, 'wrapper'=>$callable] $storageWrappers
  16. */
  17. private $storageWrappers = [];
  18. public function addStorageWrapper($wrapperName, $callback, $priority = 50, $existingMounts = []): bool {
  19. if (isset($this->storageWrappers[$wrapperName])) {
  20. return false;
  21. }
  22. // apply to existing mounts before registering it to prevent applying it double in MountPoint::createStorage
  23. foreach ($existingMounts as $mount) {
  24. $mount->wrapStorage($callback);
  25. }
  26. $this->storageWrappers[$wrapperName] = ['wrapper' => $callback, 'priority' => $priority];
  27. return true;
  28. }
  29. /**
  30. * Remove a storage wrapper by name.
  31. * Note: internal method only to be used for cleanup
  32. *
  33. * @param string $wrapperName name of the wrapper
  34. * @internal
  35. */
  36. public function removeStorageWrapper($wrapperName): void {
  37. unset($this->storageWrappers[$wrapperName]);
  38. }
  39. /**
  40. * Create an instance of a storage and apply the registered storage wrappers
  41. *
  42. * @param string $class
  43. * @param array $arguments
  44. * @return IStorage
  45. */
  46. public function getInstance(IMountPoint $mountPoint, $class, $arguments): IStorage {
  47. if (!is_a($class, IConstructableStorage::class, true)) {
  48. \OCP\Server::get(LoggerInterface::class)->warning('Building a storage not implementing IConstructableStorage is deprecated since 31.0.0', ['class' => $class]);
  49. }
  50. return $this->wrap($mountPoint, new $class($arguments));
  51. }
  52. /**
  53. * @param IStorage $storage
  54. */
  55. public function wrap(IMountPoint $mountPoint, $storage): IStorage {
  56. $wrappers = array_values($this->storageWrappers);
  57. usort($wrappers, function ($a, $b) {
  58. return $b['priority'] - $a['priority'];
  59. });
  60. /** @var callable[] $wrappers */
  61. $wrappers = array_map(function ($wrapper) {
  62. return $wrapper['wrapper'];
  63. }, $wrappers);
  64. foreach ($wrappers as $wrapper) {
  65. $storage = $wrapper($mountPoint->getMountPoint(), $storage, $mountPoint);
  66. if (!($storage instanceof IStorage)) {
  67. throw new \Exception('Invalid result from storage wrapper');
  68. }
  69. }
  70. return $storage;
  71. }
  72. }