1 | <?php |
||
13 | class NativeHttpClient implements HttpClientInterface |
||
14 | { |
||
15 | /** |
||
16 | * @var \Marek\Toggable\API\Security\TokenInterface |
||
17 | */ |
||
18 | private $token; |
||
19 | |||
20 | /** |
||
21 | * @var string |
||
22 | */ |
||
23 | private $url; |
||
24 | |||
25 | /** |
||
26 | * NativeHttpClient constructor. |
||
27 | * |
||
28 | * @param string $url |
||
29 | * @param \Marek\Toggable\API\Security\TokenInterface $token |
||
30 | */ |
||
31 | 13 | public function __construct($url, \Marek\Toggable\API\Security\TokenInterface $token) |
|
36 | |||
37 | /** |
||
38 | * @inheritDoc |
||
39 | */ |
||
40 | public function send(\Marek\Toggable\API\Http\Request\RequestInterface $request) |
||
|
|||
41 | { |
||
42 | $opts = array( |
||
43 | 'http' => array( |
||
44 | 'method' => $request->getMethod(), |
||
45 | 'header' => array( |
||
46 | 'Content-type: application/json', |
||
47 | ), |
||
48 | ), |
||
49 | ); |
||
50 | |||
51 | if (session_status() === PHP_SESSION_ACTIVE && !empty($_SESSION[SessionCookieInterface::COOKIE_NAME])) { |
||
52 | |||
53 | $opts['http']['header'][] = 'Cookie ' . $_SESSION[SessionCookieInterface::COOKIE_NAME]; |
||
54 | |||
55 | } else { |
||
56 | |||
57 | $auth = $this->token->getAuthentication(); |
||
58 | $auth = $auth[0] . ':' . $auth[1]; |
||
59 | $auth = base64_encode($auth); |
||
60 | $opts['http']['header'][] = 'Authorization: Basic ' . $auth; |
||
61 | |||
62 | } |
||
63 | |||
64 | if (!empty($request->getData())) { |
||
65 | $opts['http']['content'] = json_encode($request); |
||
66 | } |
||
67 | |||
68 | $context = stream_context_create($opts); |
||
69 | |||
70 | $url = $this->url . '/' . $request->getUri(); |
||
71 | $stream = @fopen($url, 'r', false, $context); |
||
72 | |||
73 | if ($stream == false) { |
||
74 | throw new NetworkException("Error while trying to connect to Toggl"); |
||
75 | } |
||
76 | |||
77 | $data = stream_get_contents($stream); |
||
78 | if ($data === false) { |
||
79 | throw new ServerException("Error reading response data."); |
||
80 | } |
||
81 | |||
82 | $metadata = stream_get_meta_data($stream); |
||
83 | fclose($stream); |
||
84 | |||
85 | return new HttpClientResponse($data, $metadata); |
||
86 | } |
||
87 | |||
88 | /** |
||
89 | * @inheritDoc |
||
90 | */ |
||
91 | public function setToken(\Marek\Toggable\API\Security\TokenInterface $token) |
||
95 | |||
96 | /** |
||
97 | * @inheritDoc |
||
98 | */ |
||
99 | public function setCookie(\Marek\Toggable\API\Security\Cookie\SessionCookieInterface $cookie) |
||
107 | } |
||
108 |
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: