Hooks.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OC\Accounts;
  7. use OCP\Accounts\IAccountManager;
  8. use OCP\Accounts\PropertyDoesNotExistException;
  9. use OCP\EventDispatcher\Event;
  10. use OCP\EventDispatcher\IEventListener;
  11. use OCP\IUser;
  12. use OCP\User\Events\UserChangedEvent;
  13. use Psr\Log\LoggerInterface;
  14. /**
  15. * @template-implements IEventListener<UserChangedEvent>
  16. */
  17. class Hooks implements IEventListener {
  18. public function __construct(
  19. private LoggerInterface $logger,
  20. private IAccountManager $accountManager,
  21. ) {
  22. }
  23. /**
  24. * update accounts table if email address or display name was changed from outside
  25. */
  26. public function changeUserHook(IUser $user, string $feature, $newValue): void {
  27. $account = $this->accountManager->getAccount($user);
  28. try {
  29. switch ($feature) {
  30. case 'eMailAddress':
  31. $property = $account->getProperty(IAccountManager::PROPERTY_EMAIL);
  32. break;
  33. case 'displayName':
  34. $property = $account->getProperty(IAccountManager::PROPERTY_DISPLAYNAME);
  35. break;
  36. }
  37. } catch (PropertyDoesNotExistException $e) {
  38. $this->logger->debug($e->getMessage(), ['exception' => $e]);
  39. return;
  40. }
  41. if (isset($property) && $property->getValue() !== (string)$newValue) {
  42. $property->setValue($newValue);
  43. $this->accountManager->updateAccount($account);
  44. }
  45. }
  46. public function handle(Event $event): void {
  47. if (!$event instanceof UserChangedEvent) {
  48. return;
  49. }
  50. $this->changeUserHook($event->getUser(), $event->getFeature(), $event->getValue());
  51. }
  52. }