1
0

DisplayNameCache.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Group;
  8. use OCP\Cache\CappedMemoryCache;
  9. use OCP\EventDispatcher\Event;
  10. use OCP\EventDispatcher\IEventListener;
  11. use OCP\Group\Events\GroupChangedEvent;
  12. use OCP\Group\Events\GroupDeletedEvent;
  13. use OCP\ICache;
  14. use OCP\ICacheFactory;
  15. use OCP\IGroupManager;
  16. /**
  17. * Class that cache the relation Group ID -> Display name
  18. *
  19. * This saves fetching the group from the backend for "just" the display name
  20. * @template-implements IEventListener<GroupChangedEvent|GroupDeletedEvent>
  21. */
  22. class DisplayNameCache implements IEventListener {
  23. private CappedMemoryCache $cache;
  24. private ICache $memCache;
  25. private IGroupManager $groupManager;
  26. public function __construct(ICacheFactory $cacheFactory, IGroupManager $groupManager) {
  27. $this->cache = new CappedMemoryCache();
  28. $this->memCache = $cacheFactory->createDistributed('groupDisplayNameMappingCache');
  29. $this->groupManager = $groupManager;
  30. }
  31. public function getDisplayName(string $groupId): ?string {
  32. if (isset($this->cache[$groupId])) {
  33. return $this->cache[$groupId];
  34. }
  35. $displayName = $this->memCache->get($groupId);
  36. if ($displayName) {
  37. $this->cache[$groupId] = $displayName;
  38. return $displayName;
  39. }
  40. $group = $this->groupManager->get($groupId);
  41. if ($group) {
  42. $displayName = $group->getDisplayName();
  43. } else {
  44. $displayName = null;
  45. }
  46. $this->cache[$groupId] = $displayName;
  47. $this->memCache->set($groupId, $displayName, 60 * 10); // 10 minutes
  48. return $displayName;
  49. }
  50. public function clear(): void {
  51. $this->cache = new CappedMemoryCache();
  52. $this->memCache->clear();
  53. }
  54. public function handle(Event $event): void {
  55. if ($event instanceof GroupChangedEvent && $event->getFeature() === 'displayName') {
  56. $groupId = $event->getGroup()->getGID();
  57. $newDisplayName = $event->getValue();
  58. $this->cache[$groupId] = $newDisplayName;
  59. $this->memCache->set($groupId, $newDisplayName, 60 * 10); // 10 minutes
  60. }
  61. if ($event instanceof GroupDeletedEvent) {
  62. $groupId = $event->getGroup()->getGID();
  63. unset($this->cache[$groupId]);
  64. $this->memCache->remove($groupId);
  65. }
  66. }
  67. }