1
0

CapabilitiesManager.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC;
  9. use OCP\AppFramework\QueryException;
  10. use OCP\Capabilities\ICapability;
  11. use OCP\Capabilities\IInitialStateExcludedCapability;
  12. use OCP\Capabilities\IPublicCapability;
  13. use Psr\Log\LoggerInterface;
  14. class CapabilitiesManager {
  15. /** @var \Closure[] */
  16. private $capabilities = [];
  17. /** @var LoggerInterface */
  18. private $logger;
  19. public function __construct(LoggerInterface $logger) {
  20. $this->logger = $logger;
  21. }
  22. /**
  23. * Get an array of al the capabilities that are registered at this manager
  24. *
  25. * @param bool $public get public capabilities only
  26. * @throws \InvalidArgumentException
  27. * @return array<string, mixed>
  28. */
  29. public function getCapabilities(bool $public = false, bool $initialState = false) : array {
  30. $capabilities = [];
  31. foreach ($this->capabilities as $capability) {
  32. try {
  33. $c = $capability();
  34. } catch (QueryException $e) {
  35. $this->logger->error('CapabilitiesManager', [
  36. 'exception' => $e,
  37. ]);
  38. continue;
  39. }
  40. if ($c instanceof ICapability) {
  41. if (!$public || $c instanceof IPublicCapability) {
  42. if ($initialState && ($c instanceof IInitialStateExcludedCapability)) {
  43. // Remove less important capabilities information that are expensive to query
  44. // that we would otherwise inject to every page load
  45. continue;
  46. }
  47. $capabilities = array_replace_recursive($capabilities, $c->getCapabilities());
  48. }
  49. } else {
  50. throw new \InvalidArgumentException('The given Capability (' . get_class($c) . ') does not implement the ICapability interface');
  51. }
  52. }
  53. return $capabilities;
  54. }
  55. /**
  56. * In order to improve lazy loading a closure can be registered which will be called in case
  57. * capabilities are actually requested
  58. *
  59. * $callable has to return an instance of OCP\Capabilities\ICapability
  60. *
  61. * @param \Closure $callable
  62. */
  63. public function registerCapability(\Closure $callable) {
  64. $this->capabilities[] = $callable;
  65. }
  66. }