DataUsageManager   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 31
dl 0
loc 74
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B get() 0 43 7
A __construct() 0 4 1
1
<?php declare(strict_types=1);
2
3
namespace Audiens\AdForm\Manager;
4
5
use Audiens\AdForm\Cache\CacheInterface;
6
use Audiens\AdForm\Exception\ApiException;
7
use Audiens\AdForm\HttpClient;
8
use DateTime;
9
use GuzzleHttp\Exception\ClientException;
10
11
class DataUsageManager
12
{
13
    /** @var HttpClient */
14
    protected $httpClient;
15
16
    /** @var CacheInterface|null */
17
    protected $cache;
18
19
    /** @var string */
20
    protected $cachePrefix = 'datausage';
21
22
    public function __construct(HttpClient $httpClient, CacheInterface $cache = null)
23
    {
24
        $this->httpClient = $httpClient;
25
        $this->cache = $cache;
26
    }
27
28
    /**
29
     * Returns an array of data usage objects
30
     *
31
     * @param int $dataProviderId
32
     * @param DateTime $from
33
     * @param DateTime $to
34
     * @param array $groupBy
35
     * @param int $limit
36
     * @param int $offset
37
     *
38
     * @throws ApiException if the API call fails
39
     *
40
     * @return array
41
     */
42
    public function get(int $dataProviderId, DateTime $from, DateTime $to, array $groupBy, int $limit = 1000, int $offset = 0): array
43
    {
44
        // Endpoint URI
45
        $uri = 'v1/reports/datausage';
46
47
        $options = [
48
            'query' => [
49
                'dataProviderId' => $dataProviderId,
50
                'from' => $from->format('c'),
51
                'to' => $to->format('c'),
52
                'groupBy' => $groupBy,
53
                'limit' => $limit,
54
                'offset' => $offset,
55
            ],
56
        ];
57
58
        try {
59
            $data = null;
60
61
            // try to get from cache
62
            if ($this->cache) {
63
                $data = $this->cache->get($this->cachePrefix, $uri, $options);
64
            }
65
66
            // load from API
67
            if (!$data) {
68
                $data = $this->httpClient->get($uri, $options)->getBody()->getContents();
69
70
                if ($this->cache && $data) {
71
                    $this->cache->put($this->cachePrefix, $uri, $options, $data);
72
                }
73
            }
74
75
            return \json_decode($data);
76
        } catch (ClientException $e) {
77
            $response = $e->getResponse();
78
            if ($response === null) {
79
                throw $e;
80
            }
81
            $responseBody = $response->getBody()->getContents();
82
            $responseCode = $response->getStatusCode();
83
84
            throw new ApiException($responseBody, $responseCode);
85
        }
86
87
    }
88
}
89