nextcloud_webdav_client-1.0.x-dev/src/NextCloudUserTokenStorage.php

src/NextCloudUserTokenStorage.php
<?php

namespace Drupal\nextcloud_webdav_client;

use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
use Drupal\nextcloud_webdav_client\Entity\NextCloudUserToken;
use Drupal\user\UserInterface;

/**
 * Storage handler for NextCloud User Token entities.
 */
class NextCloudUserTokenStorage extends SqlContentEntityStorage implements NextCloudUserTokenStorageInterface {

  /**
   * {@inheritdoc}
   */
  public function loadByUser(UserInterface $user): ?NextCloudUserToken {
    $entities = $this->loadByProperties(['uid' => $user->id()]);
    return $entities ? reset($entities) : NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function loadByUserId(int $uid): ?NextCloudUserToken {
    $entities = $this->loadByProperties(['uid' => $uid]);
    return $entities ? reset($entities) : NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function createForUser(UserInterface $user, array $token_data): NextCloudUserToken {
    // Check if token already exists for this user.
    $existing = $this->loadByUser($user);
    if ($existing) {
      // Update existing token.
      return $this->updateToken($existing, $token_data);
    }

    // Create new token entity.
    $values = [
      'uid' => $user->id(),
      'access_token' => $token_data['access_token'],
      'refresh_token' => $token_data['refresh_token'] ?? NULL,
      'token_expiry' => $token_data['token_expiry'] ?? NULL,
      'nextcloud_username' => $token_data['nextcloud_username'],
    ];

    /** @var \Drupal\nextcloud_webdav_client\Entity\NextCloudUserToken $entity */
    $entity = $this->create($values);
    $entity->save();

    return $entity;
  }

  /**
   * {@inheritdoc}
   */
  public function updateToken(NextCloudUserToken $token, array $token_data): NextCloudUserToken {
    if (isset($token_data['access_token'])) {
      $token->setAccessToken($token_data['access_token']);
    }

    if (isset($token_data['refresh_token'])) {
      $token->setRefreshToken($token_data['refresh_token']);
    }

    if (isset($token_data['token_expiry'])) {
      $token->setTokenExpiry($token_data['token_expiry']);
    }

    if (isset($token_data['nextcloud_username'])) {
      $token->setNextCloudUsername($token_data['nextcloud_username']);
    }

    $token->save();

    return $token;
  }

  /**
   * {@inheritdoc}
   */
  public function deleteForUser(UserInterface $user): bool {
    $token = $this->loadByUser($user);
    if ($token) {
      $token->delete();
      return TRUE;
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function hasValidToken(UserInterface $user): bool {
    $token = $this->loadByUser($user);
    if (!$token) {
      return FALSE;
    }

    return !$token->isExpired();
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc