Completed
Pull Request — master (#12)
by Sergey
02:44
created

Request::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 5
c 1
b 0
f 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace seregazhuk\HeadHunterApi;
4
5
6
use seregazhuk\HeadHunterApi\Contracts\HttpInterface;
7
use seregazhuk\HeadHunterApi\Contracts\RequestInterface;
8
use seregazhuk\HeadHunterApi\Exceptions\HeadHunterApiException;
9
10
class Request implements RequestInterface
11
{
12
    /**
13
     * @var HttpInterface
14
     */
15
    protected $client;
16
17
    /**
18
     * @var null|string
19
     */
20
    protected $token;
21
22
    public function __construct(HttpInterface $http, $token = null)
23
    {
24
        $this->client = $http;
25
        $this->token = $token;
26
    }
27
28
    /**
29
     * @param string $uri
30
     * @param array $params
31
     * @return array|null
32
     */
33
    public function get($uri, $params = [])
34
    {
35
        $headers = $this->createHeaders();
36
37
        return $this->client->get($uri, $params, $headers);
38
    }
39
40
    /**
41
     * @param string $uri
42
     * @param array $params
43
     * @return array
44
     */
45
    public function post($uri, $params = [])
46
    {
47
        $headers = $this->createHeaders();
48
49
        return $this->client->post($uri, $params, $headers);
50
    }
51
52
    public function delete($uri)
53
    {
54
        $headers = $this->createHeaders();
55
56
        return $this->client->delete($uri, $headers);
57
    }
58
59
    /**
60
     * @return array|null
61
     */
62
    protected function createHeaders()
63
    {
64
        $headers = null;
65
66
        if(isset($this->token)) $headers['Authorization'] = 'Bearer ' . $this->token;
67
68
        return $headers;
69
    }
70
71
    /**
72
     * @param string $requestMethod
73
     * @param string $uri
74
     * @param array $params
75
     * @return mixed
76
     * @throws HeadHunterApiException
77
     */
78
    public function makeRequestCall($requestMethod, $uri, $params = [])
79
    {
80
        $requestMethod = strtolower($requestMethod);
81
82
        if(!method_exists($this->client, $requestMethod)) {
83
            throw new HeadHunterApiException("Request method $requestMethod not found");
84
        }
85
86
        $params['headers'] = $this->createHeaders();
87
88
        return $this->client->$requestMethod($uri, $params,  $this->createHeaders());
89
    }
90
}