Skip to content

Commit

Permalink
Update to use PHPStan
Browse files Browse the repository at this point in the history
  • Loading branch information
tyiuhc committed Dec 28, 2023
1 parent 4a187eb commit dca6c02
Show file tree
Hide file tree
Showing 28 changed files with 292 additions and 86 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,6 @@ jobs:

- name: Run test suite
run: composer run-script test

- name: Run PHPStan
run: vendor/bin/phpstan analyse --ansi
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
},
"require-dev": {
"phpunit/phpunit": "9.*",
"phpstan/phpstan": "^1.0"
"phpstan/phpstan": "^1"
},
"suggest": {
"monolog/monolog": "Allows more advanced logging of the application flow"
Expand Down
44 changes: 22 additions & 22 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
parameters:
level: 8
paths:
- src

excludePaths:
- src/Assignment/AssignmentConfigBuilder.php
- src/EvaluationCore

scanFiles:
- src/EvaluationCore/Util.php
20 changes: 15 additions & 5 deletions src/Amplitude/Amplitude.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,29 @@
class Amplitude
{
private string $apiKey;
/**
* @var array<array<string,mixed>>
*/
protected array $queue = [];
protected FetchClientInterface $httpClient;
private LoggerInterface $logger;
private ?AmplitudeConfig $config;
private AmplitudeConfig $config;

public function __construct(string $apiKey, LoggerInterface $logger, AmplitudeConfig $config = null)
{
$this->apiKey = $apiKey;
$this->logger = $logger;
$this->config = $config ?? AmplitudeConfig::builder()->build();
$this->httpClient = $config->fetchClient ?? $this->config->fetchClient ?? new GuzzleFetchClient($this->config->guzzleClientConfig);
$this->httpClient = $this->config->fetchClient ?? $this->config->fetchClient ?? new GuzzleFetchClient($this->config->guzzleClientConfig);
}

public function flush()
public function flush(): void
{
$payload = ["api_key" => $this->apiKey, "events" => $this->queue, "options" => ["min_id_length" => $this->config->minIdLength]];
$this->post($this->config->serverUrl, $payload);
}

public function logEvent(Event $event)
public function logEvent(Event $event): void
{
$this->queue[] = $event->toArray();
if (count($this->queue) >= $this->config->flushQueueSize) {
Expand All @@ -50,10 +53,17 @@ public function __destruct()
}
}

private function post(string $url, array $payload)
/**
* @param array<string,mixed> $payload
*/
private function post(string $url, array $payload): void
{
$fetchClient = $this->httpClient->getClient();
$payloadJson = json_encode($payload);
if ($payloadJson === false) {
$this->logger->error('[Amplitude] Failed to encode payload: ' . json_last_error());
return;
}
$request = $this->httpClient->createRequest('POST', $url)->withHeader('json', $payloadJson);
try {
$response = $fetchClient->sendRequest($request);
Expand Down
8 changes: 7 additions & 1 deletion src/Amplitude/AmplitudeConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,11 @@ class AmplitudeConfig
/**
* True to use batch API endpoint, False to use HTTP V2 API endpoint.
*/
public string $useBatch;
public bool $useBatch;
public ?FetchClientInterface $fetchClient;
/**
* @var array<string, mixed>
*/
public array $guzzleClientConfig;

const DEFAULTS = [
Expand All @@ -56,6 +59,9 @@ class AmplitudeConfig
'guzzleClientConfig' => []
];

/**
* @param array<string, mixed> $guzzleClientConfig
*/
public function __construct(
int $flushQueueSize,
int $minIdLength,
Expand Down
8 changes: 7 additions & 1 deletion src/Amplitude/AmplitudeConfigBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ class AmplitudeConfigBuilder
protected ?string $serverUrl = null;
protected bool $useBatch = AmplitudeConfig::DEFAULTS['useBatch'];
protected ?FetchClientInterface $fetchClient = AmplitudeConfig::DEFAULTS['fetchClient'];
/**
* @var array<string, mixed>
*/
protected array $guzzleClientConfig = AmplitudeConfig::DEFAULTS['guzzleClientConfig'];

public function __construct()
Expand Down Expand Up @@ -54,13 +57,16 @@ public function fetchClient(FetchClientInterface $fetchClient): AmplitudeConfigB
return $this;
}

/**
* @param array<string, mixed> $guzzleClientConfig
*/
public function guzzleClientConfig(array $guzzleClientConfig): AmplitudeConfigBuilder
{
$this->guzzleClientConfig = $guzzleClientConfig;
return $this;
}

public function build()
public function build(): AmplitudeConfig
{
if (!$this->serverUrl) {
if ($this->useBatch) {
Expand Down
9 changes: 9 additions & 0 deletions src/Amplitude/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@
class Event
{
public ?string $eventType = null;
/**
* @var ?array<mixed>
*/
public ?array $eventProperties = null;
/**
* @var ?array<mixed>
*/
public ?array $userProperties = null;
public ?string $userId = null;
public ?string $deviceId = null;
Expand All @@ -16,6 +22,9 @@ public function __construct(string $eventType)
$this->eventType = $eventType;
}

/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return array_filter([
Expand Down
20 changes: 11 additions & 9 deletions src/AmplitudeCookie.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,25 +37,24 @@ public static function cookieName(string $amplitudeApiKey, bool $newFormat = fal
/**
* @param string $amplitudeCookie A string from the amplitude cookie
* @param bool $newFormat True if the cookie is in the Browser SDK 2.0 format
* @return array An array containing device_id and user_id (if available)
* @return array<mixed> An array containing device_id and user_id (if available)
*/
public static function parse(string $amplitudeCookie, bool $newFormat = false): array
{
if ($newFormat) {
$decoding = base64_decode($amplitudeCookie);
$decoded = urldecode($decoding);

try {
$userSession = json_decode($decoded, true);
return [
'deviceId' => $userSession['deviceId'],
'userId' => $userSession['userId'] ?? null,
];
} catch (\Exception $e) {
$userSession = json_decode($decoded, true);
if ($userSession === null) {
$logger = new InternalLogger(new DefaultLogger(), LogLevel::INFO);
$logger->error("Error parsing the Amplitude cookie: '{$amplitudeCookie}'. " . $e->getMessage());
$logger->error("Error parsing the Amplitude cookie: '{$amplitudeCookie}'.");
return [];
}
return [
'deviceId' => $userSession['deviceId'],
'userId' => $userSession['userId'] ?? null,
];
}

$values = explode('.', $amplitudeCookie);
Expand Down Expand Up @@ -92,6 +91,9 @@ public static function generate(string $deviceId, bool $newFormat = false): stri
];

$json_data = json_encode($userSessionHash);
if ($json_data === false) {
return '';
}
$encoded_json = urlencode($json_data);
return base64_encode($encoded_json);
}
Expand Down
9 changes: 8 additions & 1 deletion src/Assignment/Assignment.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,25 @@
namespace AmplitudeExperiment\Assignment;

use AmplitudeExperiment\User;
use AmplitudeExperiment\Variant;

class Assignment
{
public User $user;
/**
* @var array<string, Variant>
*/
public array $variants;
public int $timestamp;

/**
* @param array<string, Variant> $variants
*/
public function __construct(User $user, array $variants)
{
$this->user = $user;
$this->variants = $variants;
$this->timestamp = floor(microtime(true) * 1000);
$this->timestamp = (int) floor(microtime(true) * 1000);
}

public function canonicalize(): string
Expand Down
5 changes: 3 additions & 2 deletions src/Assignment/AssignmentConfigBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@

namespace AmplitudeExperiment\Assignment;

use AmplitudeExperiment\Amplitude\AmplitudeConfig;
use AmplitudeExperiment\Amplitude\AmplitudeConfigBuilder;

/**
* Extends AmplitudeConfigBuilder to allow configuration {@link AmplitudeConfig} of underlying {@link Amplitude} client.
*/

class AssignmentConfigBuilder extends AmplitudeConfigBuilder
{
protected string $apiKey;
protected int $cacheCapacity = AssignmentConfig::DEFAULTS['cacheCapacity'];

public function __construct(string $apiKey)
{
parent::__construct();
Expand All @@ -24,7 +25,7 @@ public function cacheCapacity(int $cacheCapacity): AssignmentConfigBuilder
return $this;
}

public function build(): AssignmentConfig
public function build()
{
return new AssignmentConfig(
$this->apiKey,
Expand Down
Loading

0 comments on commit dca6c02

Please sign in to comment.