Skip to content

Commit

Permalink
Fix CloudflareAnalytics + add default functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Claudio-Emmolo committed Aug 1, 2024
1 parent c184200 commit 1750200
Show file tree
Hide file tree
Showing 2 changed files with 155 additions and 46 deletions.
52 changes: 44 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,57 @@

Add in your env file the following variables:
Add in your .env file the following variables:

```dotenv
CLOUDFLARE_API_TOKEN='your_cloudflare_api_token'
[//]: # (CLOUDFLARE_DEFAULT_ZONE_TAG='your_cloudflare_default_zone_tag')
```

- ### Get views between two dates
## Usage

Default use:

```php
(new \The3LabsTeam\PhpCloudflareAnalytics\CloudflareAnalytics('zoneTag'))
```
next you can use the following methods:

```php
->getLast6Hours($param, $paramType)

->getLast24Hours($param, $paramType)

->geLast7Days($param, $paramType)

->getLastMonth($param, $paramType)
```

and you can pass the following parameters to get the data:

- PARAM => `sum` or `uniq`
- PARAM TYPE
- SUM: `request`, `pageViews`, `cachedBytes`, `cachedRequests`, `threats`
- UNIQ: 'uniques'

### Example

Get the total number of requests in the last 6 hours:

```php
$cloudflare = new \The3LabsTeam\PhpCloudflareAnalytics\CloudflareAnalytics('29djm3nr...');
$cloudflare->getLast6Hours('sum', 'request');
```

Get the total number of unique visitors in the last 24 hours:

```php
(new \The3LabsTeam\PhpCloudflareAnalytics\CloudflareAnalytics())
->getViewsBetweenDates('start_date', 'end_date', 'zone_tag');
$cloudflare = new \The3LabsTeam\PhpCloudflareAnalytics\CloudflareAnalytics('29djm3nr...');
$cloudflare->getLast24Hours('uniq', 'uniques');
```

- ### Get total views between two dates
Get the total number of page views in the last 7 days:

```php
(new \The3LabsTeam\PhpCloudflareAnalytics\CloudflareAnalytics())
->getTotalViewsBetweenDates('start_date', 'end_date', 'zone_tag');
$cloudflare = new \The3LabsTeam\PhpCloudflareAnalytics\CloudflareAnalytics('29djm3nr...');
$cloudflare->geLast7Days('sum', 'pageViews');
```


149 changes: 111 additions & 38 deletions src/CloudflareAnalytics.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,17 @@
class CloudflareAnalytics {

public string $api_token;
public string $zoneTag;
public string $endpoint;

public function __construct() {
public function __construct(string $zoneTag) {
$this->api_token = env('CLOUDFLARE_API_TOKEN');
$this->zoneTag = $zoneTag;
$this->endpoint = "https://api.cloudflare.com/client/v4/graphql";
}

// ================== UTILITY ================== //

protected function graphQLQuery($query) {
$ch = curl_init($this->endpoint);
curl_setopt_array($ch, [
Expand All @@ -27,33 +31,59 @@ protected function graphQLQuery($query) {
$response = curl_exec($ch);
curl_close($ch);

return json_decode($response, true);
$response = json_decode($response, true);

if (isset($response['errors'])) {
echo $response['errors'][0]['message'];
}

return $response;
}

protected function sumTotal($response, $zonesType, $param, $paramType)
{
$response = $response['data']['viewer']['zones'][0][$zonesType];

$total = 0;
foreach ($response as $key => $value) {
$total += $value[$param][$paramType];
}

return $total;
}

// ================== DEFAULT FUNCTIONS ================== //

//TODO: Merge all the functions in one function with parameters
/**
* Get the views between two dates - Returns an array with the date as key and the views as value
* Get the total views between two dates - Returns the total views
* @param $startDate
* @param $endDate
* @param $zoneTag
* @return array
* @param $param - 'sum' | 'uniq'
* @param $paramType - sum : 'request', 'pageViews', 'cachedBytes', 'cachedRequests', 'threats' | uniq: 'uniques'
* @return int|mixed
*/
public function getViewsBetweenDates($startDate, $endDate, $zoneTag) {
public function getBetweenDates($startDate, $endDate, $param = 'sum', $paramType = 'pageViews') {
$query = <<<GRAPHQL
query {
viewer {
zones(filter: {zoneTag: "$zoneTag"}) {
zones(filter: {zoneTag: "$this->zoneTag"}) {
httpRequests1dGroups(
limit: 1000
filter: {
date_geq: "$startDate"
date_lt: "$endDate"
}
) {
dimensions {
date
}
sum {
requests
pageViews
cachedBytes
cachedRequests
threats
}
uniq {
uniques
}
}
}
Expand All @@ -62,40 +92,43 @@ public function getViewsBetweenDates($startDate, $endDate, $zoneTag) {
GRAPHQL;

$response = $this->graphQLQuery($query);
$response = $response['data']['viewer']['zones'][0]['httpRequests1dGroups'];

$parsedResponse = [];
foreach ($response as $key => $value) {
$parsedResponse[$value['dimensions']['date']] = $value['sum']['requests'];
}
//order by date
ksort($parsedResponse);


return $parsedResponse;
return $this->sumTotal($response, 'httpRequests1dGroups', $param, $paramType);
}

/**
* Get the total views between two dates - Returns the total views
* @param $startDate
* @param $endDate
* @param $zoneTag
* @return int|mixed
* Get the total views between two dates - Return the total views
* @param $sub
* @return array
*/
public function getTotalViewsBetweenDates($startDate, $endDate, $zoneTag) {
public function getBetweenHours($sub, $param, $paramType)
{
// Current date/time in ISO 8601 format
$endDate = date('c');
$startDate = date('c', strtotime($sub));

$query = <<<GRAPHQL
query {
query {
viewer {
zones(filter: {zoneTag: "$zoneTag"}) {
httpRequests1dGroups(
zones(filter: {zoneTag: "$this->zoneTag"}) {
httpRequests1hGroups(
limit: 1000
filter: {
date_geq: "$startDate"
date_lt: "$endDate"
datetime_geq: "$startDate"
datetime_lt: "$endDate"
}
) {
dimensions {
datetime
}
sum {
requests
pageViews
cachedBytes
cachedRequests
threats
}
uniq {
uniques
}
}
}
Expand All @@ -104,13 +137,53 @@ public function getTotalViewsBetweenDates($startDate, $endDate, $zoneTag) {
GRAPHQL;

$response = $this->graphQLQuery($query);
$response = $response['data']['viewer']['zones'][0]['httpRequests1dGroups'];

$total = 0;
foreach ($response as $key => $value) {
$total += $value['sum']['requests'];
}
return $this->sumTotal($response, 'httpRequests1hGroups', $param, $paramType);
}

return $total;
// ================== DEFAULT PRESET ================== //

/**
* Get the total views last 6 hours - Returns the total views
* @return int|mixed
*/
public function getLast6Hours($param, $paramType)
{
return $this->getBetweenHours(sub: '-6 hours', param: $param, paramType: $paramType);
}

/**
* Get the total views last 24 hours - Returns the total views
* @return int|mixed
*/
public function getLast24Hours($param, $paramType)
{
return $this->getBetweenHours(sub: '-24 hours', param: $param, paramType: $paramType);
}

/**
* Get the total views last 7 days - Returns the total views
* @return int|mixed
*/
public function getLast7Days($param, $paramType)
{
// Current date/time in Y-m-d
$startDate = date('Y-m-d', strtotime('-7 days'));
$endDate = date('Y-m-d');

return $this->getBetweenDates(startDate: $startDate, endDate: $endDate, param: $param, paramType: $paramType);
}

/**
* Get the total views last month - Returns the total views
* @return int|mixed
*/
public function getLastMonth($param, $paramType)
{
// Current date/time in Y-m-d
$startDate = date('Y-m-d', strtotime('-1 month'));
$endDate = date('Y-m-d');

return $this->getBetweenDates(startDate: $startDate, endDate: $endDate, param: $param, paramType: $paramType);
}
}

0 comments on commit 1750200

Please sign in to comment.