Completed
Push — master ( 83cb8e...7577e4 )
by Josh
30:26
created

Cached::getClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
3
/**
4
* @package   s9e\TextFormatter
5
* @copyright Copyright (c) 2010-2018 The s9e Authors
6
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
7
*/
8
namespace s9e\TextFormatter\Utils\Http\Clients;
9
10
use s9e\TextFormatter\Utils\Http\Client;
11
12
class Cached extends Client
13
{
14
	/**
15
	* @var Client
16
	*/
17
	public $client;
18
19
	/**
20
	* @var string
21
	*/
22
	public $cacheDir;
23
24
	/**
25
	* @param Client $client
26
	*/
27
	public function __construct(Client $client)
28
	{
29
		$this->client        = $client;
30
		$this->timeout       = $client->timeout;
31
		$this->sslVerifyPeer = $client->sslVerifyPeer;
32
	}
33
34
	/**
35
	* {@inheritdoc}
36
	*/
37
	public function get($url, $headers = [])
38
	{
39
		$filepath = $this->getCachedFilepath([$url, $headers]);
40
		if (isset($filepath) && file_exists(preg_replace('(^compress\\.zlib://)', '', $filepath)))
41
		{
42
			return file_get_contents($filepath);
43
		}
44
45
		$content = $this->getClient()->get($url, $headers);
46
		if (isset($filepath) && $content !== false)
47
		{
48
			file_put_contents($filepath, $content);
49
		}
50
51
		return $content;
52
	}
53
54
	/**
55
	* {@inheritdoc}
56
	*/
57
	public function post($url, $headers = [], $body = '')
58
	{
59
		return $this->getClient()->post($url, $headers, $body);
60
	}
61
62
	/**
63
	* Generate and return a filepath that matches given vars
64
	*
65
	* @param  array  $vars
66
	* @return string
67
	*/
68
	protected function getCachedFilepath(array $vars)
69
	{
70
		if (!isset($this->cacheDir))
71
		{
72
			return null;
73
		}
74
75
		$filepath = $this->cacheDir . '/http.' . $this->getCacheKey($vars);
76
		if (extension_loaded('zlib'))
77
		{
78
			$filepath = 'compress.zlib://' . $filepath . '.gz';
79
		}
80
81
		return $filepath;
82
	}
83
84
85
	/**
86
	* Generate a key for a given set of values
87
	*
88
	* @param  string[] $vars
89
	* @return string
90
	*/
91
	protected function getCacheKey(array $vars)
92
	{
93
		return strtr(base64_encode(sha1(serialize($vars), true)), '/', '_');
94
	}
95
96
	/**
97
	* Return cached client configured with this client's options
98
	*
99
	* @return Client
100
	*/
101
	protected function getClient()
102
	{
103
		$this->client->timeout       = $this->timeout;
104
		$this->client->sslVerifyPeer = $this->sslVerifyPeer;
105
106
		return $this->client;
107
	}
108
}