Skip to content

Commit

Permalink
Merge pull request #170 from 5pm-HDH/feat/2/ct-session
Browse files Browse the repository at this point in the history
feat(ct-session): create ct-session to manage multiple connections #2
  • Loading branch information
DumbergerL authored Jun 28, 2023
2 parents 661f26b + c87fee3 commit d21fbce
Show file tree
Hide file tree
Showing 9 changed files with 275 additions and 39 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Pagination Page-Size Option ([PR163](https://github.com/5pm-HDH/churchtools-api/pull/163))
- DateTime-Getter ([PR167](https://github.com/5pm-HDH/churchtools-api/pull/167))
- Song-Tags ([PR168](https://github.com/5pm-HDH/churchtools-api/pull/168))
- CTSession ([PR170](https://github.com/5pm-HDH/churchtools-api/pull/170))

### Changed
- Refactor Imports ([PR165](https://github.com/5pm-HDH/churchtools-api/pull/165))
Expand Down
30 changes: 27 additions & 3 deletions docs/out/CTConfig.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,31 @@ $success = CTConfig::authWithUserIdAndLoginToken("29", "<login-token>");

```

## 3. Cache Requests
## 3. CT-Session

To manage various ChurchTools connections with different logins within a single application, you can utilize the CTSession feature to switch between different configurations.

To create and switch to a new session, use the following code:

```php
use CTApi\CTSession;

CTSession::switchSession("person_a_session");

```

When switching to a new session, you need to reinitialize the ChurchTools API and authenticate the client.

By default, if no session configuration is specified, the "default" session is used. To switch back to the default session, you can use the following code:

```php
use CTApi\CTSession;

CTSession::switchSession();

```

## 4. Cache Requests

To increase performance enable the caching-mechanism with:

Expand Down Expand Up @@ -137,7 +161,7 @@ $response = $client->get(

```

## 4. Pagination
## 5. Pagination

Set Page-Size of Pagination-Requests.

Expand All @@ -148,7 +172,7 @@ CTConfig::setPaginationPageSize(400);

```

## 5. CSRF-Token
## 6. CSRF-Token

```php
use CTApi\Requests\CSRFTokenRequest;
Expand Down
28 changes: 25 additions & 3 deletions docs/src/ressources/CTConfig.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,29 @@ use CTApi\CTConfig;
$success = CTConfig::authWithUserIdAndLoginToken("29", "<login-token>");
```

## 3. Cache Requests
## 3. CT-Session

To manage various ChurchTools connections with different logins within a single application, you can utilize the CTSession feature to switch between different configurations.

To create and switch to a new session, use the following code:

```php
use CTApi\CTSession;

CTSession::switchSession("person_a_session");
```

When switching to a new session, you need to reinitialize the ChurchTools API and authenticate the client.

By default, if no session configuration is specified, the "default" session is used. To switch back to the default session, you can use the following code:

```php
use CTApi\CTSession;

CTSession::switchSession();
```

## 4. Cache Requests

To increase performance enable the caching-mechanism with:

Expand Down Expand Up @@ -128,7 +150,7 @@ $response = $client->get(
);
```

## 4. Pagination
## 5. Pagination

Set Page-Size of Pagination-Requests.

Expand All @@ -138,6 +160,6 @@ use CTApi\CTConfig;
CTConfig::setPaginationPageSize(400);
```

## 5. CSRF-Token
## 6. CSRF-Token

{{ \CTApi\Test\Unit\Docs\CSRFTokenRequestTest.testGetCSRFToken }}
11 changes: 4 additions & 7 deletions src/CTClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,6 @@
use GuzzleHttp\HandlerStack;
use Psr\Http\Message\ResponseInterface;

/**
* @psalm-suppress InvalidExtendClass
*/
class CTClient
{
private Client $guzzleClient;
Expand Down Expand Up @@ -109,7 +106,7 @@ private function handleException(Exception $exception): ResponseInterface
public static function getClient(): CTClient
{
if (is_null(self::$client)) {
self::createClient();
self::$client = self::createClient();
}
if (isset(self::$client)) {
return self::$client;
Expand All @@ -122,12 +119,12 @@ public static function setClient(CTClient $client): void
self::$client = $client;
}

public static function createClient(?HandlerStack $handlerStack = null): void
public static function createClient(?HandlerStack $handlerStack = null): CTClient
{
if (is_null($handlerStack)) {
self::$client = new CTClient();
return new CTClient();
} else {
self::$client = new CTClient(['handler' => $handlerStack]);
return new CTClient(['handler' => $handlerStack]);
}
}
}
58 changes: 35 additions & 23 deletions src/CTConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,12 @@ private function __construct()

public static function clearConfig(): void
{
self::$config = new CTConfig();
self::$config = CTConfig::createConfig();
}

public static function createConfig(): CTConfig
{
return new CTConfig();
}

public static function clearCookies(): void
Expand All @@ -65,17 +70,41 @@ public static function clearCookies(): void
public static function getConfig(): CTConfig
{
if (is_null(self::$config)) {
self::$config = new CTConfig();
self::$config = CTConfig::createConfig();
}
return self::$config;
}

public static function setConfig(CTConfig $config)
{
self::$config = $config;
}

private static function setRequestOption(string $path, $value): void
{
CTUtil::arrayPathSet(self::getConfig()->requestOptions, $path, $value);
}

public static function getRequestConfig(): array
{
self::validateConfig();
return self::getConfig()->requestOptions;
}

public static function validateConfig(): void
{
$apiUrl = self::getRequestOption('base_uri');
if ($apiUrl == null) {
throw new CTConfigException("CTConfig invalid: ApiUrl cannot be null. Set it with: CTConfig::setApiUrl('https://example.com')");
}
}

private static function getRequestOption(string $path)
{
$array = self::getConfig()->requestOptions;
return CTUtil::arrayPathGet($array, $path);
}

public static function setApiUrl(string $apiUrl): void
{
self::setRequestOption("base_uri", $apiUrl);
Expand Down Expand Up @@ -157,14 +186,6 @@ public static function getPaginationPageSize(): ?int
return $size;
}

public static function validateConfig(): void
{
$apiUrl = self::getRequestOption('base_uri');
if ($apiUrl == null) {
throw new CTConfigException("CTConfig invalid: ApiUrl cannot be null. Set it with: CTConfig::setApiUrl('https://example.com')");
}
}

public static function validateAuthentication(): bool
{
try {
Expand All @@ -179,17 +200,6 @@ public static function validateAuthentication(): bool
}
}

private static function setRequestOption(string $path, $value): void
{
CTUtil::arrayPathSet(self::getConfig()->requestOptions, $path, $value);
}

private static function getRequestOption(string $path)
{
$array = self::getConfig()->requestOptions;
return CTUtil::arrayPathGet($array, $path);
}

public static function enableDebugging(): void
{
CTLog::setConsoleLogLevelDebug();
Expand Down Expand Up @@ -224,13 +234,15 @@ public static function enableCache(?int $timeToLive = null): void
$stack->push(CTCacheMiddleware::create());

CTLog::getLog()->info("CTConfig: Create cache-middleware and recreate CTClient");
CTClient::createClient($stack);
$client = CTClient::createClient($stack);
CTClient::setClient($client);
}

public static function disableCache(): void
{
CTLog::getLog()->info("CTConfig: Recreate CTClient without cache-middleware");
CTClient::createClient();
$client = CTClient::createClient();
CTClient::setClient($client);
}

public static function clearCache(): void
Expand Down
67 changes: 67 additions & 0 deletions src/CTSession.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php


namespace CTApi;


class CTSession
{
private const DEFAULT_SESSION_ID = "default";

private static array $ctConfigs = [];
private static array $ctClients = [];

public static function switchSession(string $sessionId = self::DEFAULT_SESSION_ID)
{
self::storeDefaultSessionIfNotExists();
if (!self::sessionExists($sessionId)) {
self::createSession($sessionId);
} else {
self::switchToSession($sessionId);
}
}

private static function storeDefaultSessionIfNotExists()
{
if (!self::sessionExists(self::DEFAULT_SESSION_ID)) {
self::$ctConfigs[self::DEFAULT_SESSION_ID] = CTConfig::getConfig();
self::$ctClients[self::DEFAULT_SESSION_ID] = CTClient::getClient();
}
}

private static function sessionExists(string $sessionId)
{
return array_key_exists($sessionId, self::$ctConfigs) && array_key_exists($sessionId, self::$ctClients);
}

private static function createSession(string $sessionId)
{
$config = CTConfig::createConfig();
$client = CTClient::createClient();

self::$ctConfigs[$sessionId] = $config;
self::$ctClients[$sessionId] = $client;

self::switchToSession($sessionId);
}

private static function switchToSession(string $sessionId)
{
CTConfig::setConfig(self::$ctConfigs[$sessionId]);
CTClient::setClient(self::$ctClients[$sessionId]);
}

public static function getSessionIds(): array
{
self::storeDefaultSessionIfNotExists();
$keysConfig = array_keys(self::$ctConfigs);
$keysClient = array_keys(self::$ctConfigs);
return array_intersect($keysConfig, $keysClient);
}

public static function clearSessions()
{
self::$ctClients = [];
self::$ctConfigs = [];
}
}
54 changes: 54 additions & 0 deletions tests/Integration/Config/CTSessionIntegrationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php


namespace CTApi\Test\Integration\Config;


use CTApi\CTConfig;
use CTApi\CTSession;
use CTApi\Requests\PersonRequest;
use CTApi\Test\Integration\IntegrationTestData;
use PHPUnit\Framework\TestCase;

class CTSessionIntegrationTest extends TestCase
{
public function testSwitchSession()
{
// Default Session
$this->configPersonA();
$personA = PersonRequest::whoami();

// Custom Session
CTSession::switchSession("custom_person_session");
$this->configPersonB();
$personB = PersonRequest::whoami();

// Default Session
CTSession::switchSession();
$personA_2 = PersonRequest::whoami();

// Custom Session
CTSession::switchSession("custom_person_session");
$personB_2 = PersonRequest::whoami();

$this->assertEquals($personA, $personA_2);
$this->assertEquals($personB, $personB_2);
$this->assertNotEquals($personA, $personB);
$this->assertNotEquals($personA_2, $personB_2);
$this->assertNotEquals($personA, $personB_2);
$this->assertNotEquals($personA_2, $personB);
}

private function configPersonA()
{
CTConfig::setApiUrl(IntegrationTestData::get()->getApiUrl());
IntegrationTestData::get()->authenticateUser();
}

private function configPersonB()
{
CTConfig::setApiUrl(IntegrationTestData::get()->getApiUrl());
IntegrationTestData::get()->authenticateUser("jona");
}

}
Loading

0 comments on commit d21fbce

Please sign in to comment.