Completed
Push — master ( 68eeec...2e94f3 )
by Giacomo "Mr. Wolf"
02:45
created

AudienceManager   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 11
eloc 28
dl 0
loc 68
rs 10
c 0
b 0
f 0

2 Methods

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