Skip to content

Commit

Permalink
dynamic get
Browse files Browse the repository at this point in the history
  • Loading branch information
murdercode committed Aug 2, 2024
1 parent cab2def commit 48d0e8a
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 110 deletions.
174 changes: 68 additions & 106 deletions src/CloudflareAnalytics.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ class CloudflareAnalytics

protected string $endpoint;

protected string $startDate;
protected array $selectors = [];

protected string $endDate;
protected array $filters = [];

protected ?int $limit;
protected array $orderBys = [];

protected ?string $orderBy;
protected $takes = [];

/**
* CloudflareAnalytics constructor.
Expand All @@ -31,11 +31,16 @@ public function __construct(?string $apiToken = null, ?string $zoneTag = null)
$this->apiToken = $apiToken ?? $_ENV['CLOUDFLARE_API_TOKEN'];
$this->zoneTag = $zoneTag ?? $_ENV['CLOUDFLARE_ZONE_TAG_ID'];
$this->endpoint = 'https://api.cloudflare.com/client/v4/graphql';
}

public function select(...$selectors)
{
foreach ($selectors as $selector) {
[$key, $alias] = explode(' AS ', $selector);
$this->selectors[$alias] = $key;
}

$this->startDate = (new \DateTime('-1 day'))->format('c');
$this->endDate = (new \DateTime)->format('c');
$this->limit = 1000;
$this->orderBy = 'datetime_DESC';
return $this;
}

/**
Expand Down Expand Up @@ -69,142 +74,99 @@ protected function query($query)
/**
* Get the total views between two dates - Returns the total views
*/
public function whereBetween(string $startDate, string $endDate)
public function whereBetween(string $context, string $startDate, string $endDate)
{
$this->startDate = $startDate;
$this->endDate = $endDate;
$this->filters[$context] = [
'startDate' => $startDate,
'endDate' => $endDate,
];

return $this;
}

/**
* Set the order by field and direction
*/
public function orderBy(string $field, string $direction = 'ASC')
public function orderBy(string $context, string $field, string $direction = 'ASC')
{
$this->orderBy = $field.'_'.$direction;
$this->orderBys[$context][] = $field.'_'.$direction;

return $this;
}

/**
* Get a specific number of results
*/
public function take(int $limit)
public function take($alias, $limit)
{
$this->limit = $limit;
$this->takes[$alias] = $limit;

return $this;
}

/**
* Get data
*/
public function get()
public function get(...$fields)
{

$query = <<<GRAPHQL
query {
viewer {
zones(filter: {zoneTag: "$this->zoneTag"}) {
last10Events: firewallEventsAdaptive(
filter: {
datetime_gt: "$this->startDate"
datetime_lt: "$this->endDate"
}
limit: 10
orderBy: [
datetime_DESC
]
) {
action
datetime
host: clientRequestHTTPHost
$queries = [];
foreach ($this->selectors as $alias => $selector) {
$filter = $this->filters[$alias] ?? [];
$orderBy = $this->orderBys[$alias] ?? [];
$limit = isset($this->takes[$alias]) ? $this->takes[$alias] : 10;

$fieldsList = implode("\n", array_map(fn ($f) => str_replace("$alias.", "", $f), $fields));

$queries[] = <<<GRAPHQL
$alias: $selector(
filter: {
datetime_gt: "{$filter['startDate']}"
datetime_lt: "{$filter['endDate']}"
}
top3DeviceTypes: httpRequestsAdaptiveGroups(
filter: {
datetime_gt: "$this->startDate"
datetime_lt: "$this->endDate"
}
limit: 10
orderBy: [
count_DESC
]
) {
count
dimensions {
device: clientDeviceType
}
}
}
limit: $limit
orderBy: [
{$this->formatOrderBy($orderBy)}
]
) {
$fieldsList
}
GRAPHQL;
}

$query = <<<GRAPHQL
query {
viewer {
zones(filter: {zoneTag: "$this->zoneTag"}) {
{$this->formatQueries($queries)}
}
}
GRAPHQL;
}
GRAPHQL;

$response = $this->query($query);

dd($response);

return $response;

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

// 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];
// }
private function formatOrderBy(array $orderBy)
{
return implode("\n", array_map(fn ($o) => $o, $orderBy));
}

// return $total;
// }
private function formatQueries(array $queries)
{
return implode("\n", array_map(fn ($q) => $q, $queries));
}

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

$query = <<<GRAPHQL
query {
viewer {
zones(filter: {zoneTag: "$this->zoneTag"}) {
httpRequests1hGroups(
limit: 1000
filter: {
datetime_geq: "$startDate"
datetime_lt: "$endDate"
}
) {
dimensions {
datetime
}
sum {
requests
pageViews
cachedBytes
cachedRequests
threats
}
uniq {
uniques
}
}
}
}
$takes = [];
foreach ($this->takes as $alias => $limit) {
if (is_int($limit)) {
$takes[] = "{$alias}: {$limit}";
}
GRAPHQL;

$response = $this->query($query);
}

// return $this->sumTotal($response, 'httpRequests1hGroups', $param, $paramType);
return implode(', ', $takes);
}
}
16 changes: 12 additions & 4 deletions tests/CloudflareAnalyticsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,20 @@
$this->cf = new CloudflareAnalytics;
});

it('can get total views', function () {
it('can get firewall data', function () {
$startDate = (new DateTime)->sub(new DateInterval('P1D'))->format('c');
$endDate = (new DateTime)->format('c');

$cf = new CloudflareAnalytics;
$result = $cf->get();

$this->assertIsArray($result);
$this->assertGreaterThan(0, $result);
$results = $cf->select('firewallEventsAdaptive AS firewall')
->whereBetween('firewall', $startDate, $endDate)
->orderBy('firewall.datetime', 'DESC')
->take('firewall', 2)
->get('firewall.datetime', 'firewall.action');

$this->assertIsArray($results);
$this->assertGreaterThan(0, $results);
});

// it('can get total views between two dates', function () {
Expand Down

0 comments on commit 48d0e8a

Please sign in to comment.