Completed
Push — master ( 9c70e0...8dab97 )
by Sergey
04:10 queued 01:32
created

Request::makeRequestCall()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 1
eloc 4
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
    /**
73
     * @param string $method
74
     * @param array $params
75
     * @return array
76
     * @throws HeadHunterApiException
77
     */
78
    public function __call($method, $params)
79
    {
80
        if(!preg_match('/send(.+)Request/', $method, $matches)) {
81
            throw new HeadHunterApiException("Method $method not found");
82
        };
83
84
        return $this->makeRequestCall($matches[1], $params);
85
    }
86
87
    /**
88
     * @param string $requestMethod
89
     * @param array $params
90
     * @return mixed
91
     */
92
    protected function makeRequestCall($requestMethod, $params)
93
    {
94
        $requestMethod = strtolower($requestMethod);
95
96
        $params['headers'] = $this->createHeaders();
97
98
        return $this->client->$requestMethod(...$params);
99
    }
100
}