Completed
Pull Request — master (#11)
by Sergey
02:36
created

Request   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 91
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 2
Bugs 1 Features 1
Metric Value
wmc 9
c 2
b 1
f 1
lcom 1
cbo 2
dl 0
loc 91
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A get() 0 6 1
A post() 0 6 1
A delete() 0 6 1
A createHeaders() 0 8 2
A __call() 0 8 2
A makeRequestCall() 0 8 1
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
}