1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Audiens\AdForm\Manager; |
4
|
|
|
|
5
|
|
|
use Audiens\AdForm\Cache\CacheInterface; |
6
|
|
|
use Audiens\AdForm\Entity\AudienceHydrator; |
7
|
|
|
use Audiens\AdForm\Exception\EntityNotFoundException; |
8
|
|
|
use Audiens\AdForm\HttpClient; |
9
|
|
|
use GuzzleHttp\Exception\ClientException; |
10
|
|
|
use RuntimeException; |
11
|
|
|
|
12
|
|
|
class AudienceManager |
13
|
|
|
{ |
14
|
|
|
/** @var HttpClient */ |
15
|
|
|
protected $httpClient; |
16
|
|
|
|
17
|
|
|
/** @var CacheInterface|null */ |
18
|
|
|
protected $cache; |
19
|
|
|
|
20
|
|
|
/** @var string */ |
21
|
|
|
protected $cachePrefix = 'audience'; |
22
|
|
|
|
23
|
|
|
public function __construct(HttpClient $httpClient, CacheInterface $cache = null) |
24
|
|
|
{ |
25
|
|
|
$this->httpClient = $httpClient; |
26
|
|
|
$this->cache = $cache; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Return an array of Audience based on segment ID |
31
|
|
|
**/ |
32
|
|
|
public function getItem($segmentId): ?array |
33
|
|
|
{ |
34
|
|
|
// Endpoint URI |
35
|
|
|
$uri = sprintf('v2/segments/%s/audience/totals', $segmentId); |
36
|
|
|
|
37
|
|
|
try { |
38
|
|
|
$data = null; |
39
|
|
|
|
40
|
|
|
// try to get from cache |
41
|
|
|
if ($this->cache) { |
42
|
|
|
$data = $this->cache->get($this->cachePrefix, $uri, []); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
// load from API |
46
|
|
|
if (!$data) { |
47
|
|
|
$data = $this->httpClient->get($uri)->getBody()->getContents(); |
48
|
|
|
|
49
|
|
|
if ($this->cache && $data) { |
50
|
|
|
$this->cache->put($this->cachePrefix, $uri, [], $data); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$dataDecoded = \json_decode($data); |
55
|
|
|
|
56
|
|
|
$audiences = []; |
57
|
|
|
|
58
|
|
|
if (\is_array($dataDecoded) && \count($dataDecoded) > 0) { |
59
|
|
|
foreach ($dataDecoded as $item) { |
60
|
|
|
$audiences[] = AudienceHydrator::fromStdClass($item); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return $audiences; |
65
|
|
|
|
66
|
|
|
} catch (ClientException $e) { |
67
|
|
|
$response = $e->getResponse(); |
68
|
|
|
if ($response === null) { |
69
|
|
|
throw new RuntimeException('Null response'); |
70
|
|
|
} |
71
|
|
|
$responseBody = $response->getBody()->getContents(); |
72
|
|
|
$responseCode = $response->getStatusCode(); |
73
|
|
|
|
74
|
|
|
throw EntityNotFoundException::translate($segmentId, $responseBody, $responseCode); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|