AbstractEndpoint   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 4
dl 0
loc 66
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B call() 0 22 4
1
<?php
2
3
namespace Realshadow\Redtube\Endpoints;
4
5
use GuzzleHttp\Client;
6
use JMS\Serializer\Serializer;
7
use Realshadow\Redtube\Entities\Error;
8
use Realshadow\Redtube\Filters\Filterable;
9
10
11
/**
12
 * Base endpoint
13
 *
14
 * @package Realshadow\Redtube\Endpoints
15
 * @author Lukáš Homza <[email protected]>
16
 */
17
abstract class AbstractEndpoint
18
{
19
20
    /**
21
     * Output format (json or xml)
22
     */
23
    const OUTPUT_FORMAT = 'xml';
24
25
    /**
26
     * Guzzle client
27
     *
28
     * @var Client $client
29
     */
30
    private $client;
31
32
    /**
33
     * Serializer instance
34
     *
35
     * @var Serializer $serializer
36
     */
37
    protected $serializer;
38
39
    /**
40
     * @param Client $client
41
     * @param Serializer $serializer
42
     */
43
    public function __construct(Client $client, Serializer $serializer)
44
    {
45
        $this->client = $client;
46
        $this->serializer = $serializer;
47
    }
48
49
    /**
50
     * Calls Redtubes API and process the response
51
     *
52
     * @param $method
53
     * @param Filterable|null $filter
54
     * @param string $format
55
     *
56
     * @return string
57
     * @throws \RuntimeException
58
     */
59
    protected function call($method, Filterable $filter = null, $format = self::OUTPUT_FORMAT)
60
    {
61
        $query = sprintf('?data=redtube.%s&output=%s', $method, $format);
62
63
        # -- this will allows us to expand the method by appending additional query string, e.g. video detail
64
        if ($filter) {
65
            $query .= '&' . $filter->compile();
66
        }
67
68
        $response = $this->client->get($query);
69
70
        # -- since Redtube always returns HTTP OK we have to check for errors manually
71
        $body = $response->getBody()->getContents();
72
        if ($response->getStatusCode() === 200 && strpos($body, 'error')) {
73
            $error = $this->serializer
74
                ->deserialize($body, Error::class, self::OUTPUT_FORMAT);
75
76
            throw $error->getException();
77
        }
78
79
        return $body;
80
    }
81
82
}
83