Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"format": "./vendor/bin/pint"
},
"require": {
"php": ">=8.0"
"php": ">=8.1",
"utopia-php/fetch": "^1.1"
},
"require-dev": {
"phpunit/phpunit": "^9.3",
Expand Down
82 changes: 62 additions & 20 deletions composer.lock

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

85 changes: 32 additions & 53 deletions src/Analytics/Adapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace Utopia\Analytics;

use Exception;
use Utopia\Fetch\Client;
use Utopia\Fetch\Exception as FetchException;

abstract class Adapter
{
Expand Down Expand Up @@ -106,16 +108,12 @@ public function createEvent(Event $event): bool
* Make an API call
*
*
* @throws \Exception
* @throws Exception
*/
public function call(string $method, string $path = '', array $headers = [], array $params = []): array|string
{
$headers = array_merge($this->headers, $headers);
$ch = curl_init((str_contains($path, 'http') ? $path : $this->endpoint.$path.(($method == 'GET' && ! empty($params)) ? '?'.http_build_query($params) : '')));
$responseHeaders = [];
$responseStatus = -1;
$responseType = '';
$responseBody = '';
$url = str_contains($path, 'http') ? $path : $this->endpoint.$path.(($method == 'GET' && ! empty($params)) ? '?'.http_build_query($params) : '');

switch ($headers['Content-Type']) {
case 'application/json':
Expand All @@ -131,61 +129,42 @@ public function call(string $method, string $path = '', array $headers = [], arr
break;
}

foreach ($headers as $i => $header) {
$headers[] = $i.':'.$header;
unset($headers[$i]);
$client = (new Client)
->setUserAgent(php_uname('s').'-'.php_uname('r').':php-'.phpversion())
->setAllowRedirects(true);

foreach ($headers as $key => $value) {
$client->addHeader($key, $value);
}

try {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, php_uname('s').'-'.php_uname('r').':php-'.phpversion());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($curl, $header) use (&$responseHeaders) {
$len = strlen($header);
$header = explode(':', strtolower($header), 2);

if (count($header) < 2) { // ignore invalid headers
return $len;
}

$responseHeaders[strtolower(trim($header[0]))] = trim($header[1]);

return $len;
});

if ($method != 'GET') {
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
}

$responseBody = curl_exec($ch);

$responseType = $responseHeaders['Content-Type'] ?? '';
$responseStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$response = $client->fetch(
url: $url,
method: $method,
body: $method !== 'GET' ? $query : [],
);
} catch (FetchException $e) {
throw new Exception($e->getMessage(), $e->getCode(), $e);
}
Comment thread
greptile-apps[bot] marked this conversation as resolved.

switch (substr($responseType, 0, strpos($responseType, ';'))) {
case 'application/json':
$responseBody = json_decode($responseBody, true);
break;
}
$responseHeaders = $response->getHeaders();
$responseStatus = $response->getStatusCode();
$responseBody = $response->getBody();
$responseType = trim(explode(';', $responseHeaders['content-type'] ?? '')[0]);

if (curl_errno($ch)) {
throw new Exception(curl_error($ch), $responseStatus);
}
if ($responseType === 'application/json') {
$responseBody = json_decode($responseBody, true);
}

if ($responseStatus >= 400) {
if (is_array($responseBody)) {
throw new Exception(json_encode($responseBody), $responseStatus);
} else {
throw new Exception($responseStatus.': '.$responseBody, $responseStatus);
}
if ($responseStatus >= 400) {
if (is_array($responseBody)) {
throw new Exception(json_encode($responseBody), $responseStatus);
} else {
throw new Exception($responseStatus.': '.$responseBody, $responseStatus);
}

return $responseBody;
} finally {
curl_close($ch);
}

return $responseBody;
}

/**
Expand Down
4 changes: 1 addition & 3 deletions src/Analytics/Adapter/GoogleAnalytics.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,6 @@ public function validate(Event $event): bool
]
));

$validateResponse = json_decode($validateResponse, true);

if ($validateResponse['hitParsingResult'][0]['valid'] !== true) {
throw new \Exception('Invalid event');
}
Expand Down Expand Up @@ -148,7 +146,7 @@ public function send(Event $event): bool

// Parse Debug data
if ($this->endpoint == 'https://www.google-analytics.com/debug/collect') {
return json_decode($result, true)['hitParsingResult'][0]['valid'];
return $result['hitParsingResult'][0]['valid'];
}

return true;
Expand Down
6 changes: 0 additions & 6 deletions src/Analytics/Adapter/HubSpot.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,6 @@ public function contactExists(string $email): bool|int
throw $e;
}

$result = json_decode($result, true);

if ($result && $result['id']) {
return $result['id'];
} else {
Expand Down Expand Up @@ -158,8 +156,6 @@ public function accountExists(string $name): bool|int
]],
]);

$result = json_decode($result, true);

if ($result && $result['total'] > 0 && count($result['results']) > 0) {
return $result['results'][0]['id'];
} else {
Expand Down Expand Up @@ -233,8 +229,6 @@ public function syncAssociation(string $accountId, string $contactId, string $ro

$response = $this->call('GET', '/crm/v4/objects/contact/'.$accountId.'/associations/company');

$response = json_decode($response, true);

$associationId = null;

foreach ($response['results'] as $association) {
Expand Down
4 changes: 2 additions & 2 deletions src/Analytics/Adapter/Mixpanel.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ public function appendProperties(string $distinctId, array $properties): bool
*/
public function setClientIP(string $clientIP): self
{
throw new \Exception('Not implemented');
throw new Exception('Not implemented');
}

/**
Expand All @@ -157,7 +157,7 @@ public function setClientIP(string $clientIP): self
*/
public function setUserAgent(string $userAgent): self
{
throw new \Exception('Not implemented');
throw new Exception('Not implemented');
}

public function validate(Event $event): bool
Expand Down
4 changes: 0 additions & 4 deletions src/Analytics/Adapter/Orbit.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,6 @@ public function validate(Event $event): bool
'email' => $event->getProp('email'),
]);

$listMembers = json_decode($listMembers, true);

if (empty($listMembers['data'])) {
return false;
}
Expand All @@ -164,8 +162,6 @@ public function validate(Event $event): bool
'activity_type' => $event->getType(),
]);

$activities = json_decode($activities, true);

if (empty($activities['data'])) {
throw new \Exception('Failed to find event in Orbit');
}
Expand Down
1 change: 0 additions & 1 deletion src/Analytics/Adapter/Plausible.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,6 @@ public function validate(Event $event): bool
'Content-Type' => '',
'Authorization' => 'Bearer '.$this->apiKey,
]);
$checkCreated = json_decode($checkCreated, true);

if (! isset($checkCreated['results']['visitors']['value'])) {
throw new Exception('Failed to validate event');
Expand Down
12 changes: 6 additions & 6 deletions tests/Analytics/AnalyticsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,22 @@

class AnalyticsTest extends TestCase
{
/** @var \Utopia\Analytics\Adapter\GoogleAnalytics */
/** @var GoogleAnalytics */
public $ga;

/** @var \Utopia\Analytics\Adapter\Plausible */
/** @var Plausible */
public $pa;

/** @var \Utopia\Analytics\Adapter\Orbit */
/** @var Orbit */
public $orbit;

/** @var \Utopia\Analytics\Adapter\Mixpanel */
/** @var Mixpanel */
public $mp;

/** @var \Utopia\Analytics\Adapter\HubSpot */
/** @var HubSpot */
public $hs;

/** @var \Utopia\Analytics\Adapter\ReoDev */
/** @var ReoDev */
public $reodev;

protected function setUp(): void
Expand Down
Loading