Completed
Pull Request — master (#29)
by
unknown
02:05
created

Queue::request()   D

Complexity

Conditions 10
Paths 9

Size

Total Lines 39
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 39
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 31
nc 9
nop 3

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace h4kuna\Fio\Request;
4
5
use GuzzleHttp,
6
	h4kuna\Fio,
7
	h4kuna\Fio\Response\Pay,
8
	Nette\Utils;
9
10
class Queue implements IQueue
11
{
12
13
	/** @var string[] */
14
	private static $tokens = [];
15
16
	/** @var int */
17
	private $limitLoop = 5;
18
19
	/** @var bool */
20
	private $sleep = true;
21
22
	/** @var array */
23
	private $downloadOptions = [];
24
25
	/** @var string */
26
	private $tempDir;
27
28
	public function __construct($tempDir)
29
	{
30
		$this->tempDir = $tempDir;
31
	}
32
33
	/**
34
	 * @param int $limitLoop
35
	 */
36
	public function setLimitLoop($limitLoop)
37
	{
38
		$this->limitLoop = (int) $limitLoop;
39
	}
40
41
	/**
42
	 * @param array|\Iterator $downloadOptions
43
	 */
44
	public function setDownloadOptions($downloadOptions)
45
	{
46
		foreach ($downloadOptions as $define => $value) {
47
			if (is_string($define) && defined($define)) {
48
				$define = constant($define);
49
			}
50
			$this->downloadOptions[$define] = $value;
51
		}
52
	}
53
54
	public function setSleep($sleep)
55
	{
56
		$this->sleep = (bool) $sleep;
57
	}
58
59
	/**
60
	 * @param $token
61
	 * @param string $url
62
	 * @return mixed|string
63
	 * @throws Fio\QueueLimitException
64
	 * @throws Fio\ServiceUnavailableException
65
	 */
66
	public function download($token, $url)
67
	{
68
		return $this->request($token, function (GuzzleHttp\Client $client) use ($url) {
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->request($t...tions); }, 'download'); (GuzzleHttp\Psr7\Stream) is incompatible with the return type declared by the interface h4kuna\Fio\Request\IQueue::download of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
69
			return $client->request('GET', $url, $this->downloadOptions);
70
		}, 'download');
71
	}
72
73
	/**
74
	 * @return Pay\IResponse
75
	 * @throws Fio\QueueLimitException
76
	 * @throws Fio\ServiceUnavailableException
77
	 */
78
	public function upload($url, $token, array $post, $filename)
79
	{
80
		$newPost = [];
81
		foreach ($post as $name => $value) {
82
			$newPost[] = ['name' => $name, 'contents' => $value];
83
		}
84
		$newPost[] = ['name' => 'file', 'contents' => fopen($filename, 'r')];
85
86
		$response = $this->request($token, function (GuzzleHttp\Client $client) use ($url, $newPost) {
87
			return $client->request('POST', $url, [GuzzleHttp\RequestOptions::MULTIPART => $newPost]);
88
		}, 'upload');
89
		return self::createXmlResponse($response);
90
	}
91
92
	/**
93
	 * @param $token
94
	 * @param $fallback
95
	 * @param string $action
96
	 * @return GuzzleHttp\Psr7\Stream
97
	 * @throws Fio\QueueLimitException
98
	 * @throws Fio\ServiceUnavailableException
99
	 */
100
	private function request($token, $fallback, $action)
101
	{
102
		$request = new GuzzleHttp\Client(['headers' => ['X-Powered-By' => 'h4kuna/fio']]);
103
		$tempFile = $this->loadFileName($token);
104
		$file = fopen(self::safeProtocol($tempFile), 'w');
105
		$i = 0;
106
		do {
107
			$next = false;
108
			++$i;
109
			try {
110
				$response = $fallback($request);
111
			} catch (GuzzleHttp\Exception\ClientException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ClientException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
112
				if ($e->getCode() !== self::HEADER_CONFLICT || !$this->sleep) {
113
					fclose($file);
114
					throw $e;
115
				} elseif ($i >= $this->limitLoop) {
116
					fclose($file);
117
					throw new Fio\QueueLimitException('You have limit up requests to server ' . $this->limitLoop);
118
				}
119
				self::sleep($tempFile);
120
				$next = true;
121
			} catch (GuzzleHttp\Exception\ServerException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ServerException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
122
				if($e->hasResponse()) {
123
					self::detectDownloadResponse( $e->getResponse() );
124
				}
125
				throw new Fio\ServiceUnavailableException('Service is currently unavailable');
126
			} catch (GuzzleHttp\Exception\ConnectException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ConnectException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
127
				throw new Fio\ServiceUnavailableException('Service is currently unavailable');
128
			}
129
		} while ($next);
130
		fclose($file);
131
		touch($tempFile);
132
133
		if ($action === 'download') {
134
			self::detectDownloadResponse($response);
135
		}
136
137
		return $response->getBody();
138
	}
139
140
	/**
141
	 * @param $response
142
	 * @throws Fio\ServiceUnavailableException
143
	 */
144
	private static function detectDownloadResponse($response)
145
	{
146
		/* @var $contentTypeHeaders array */
147
		$contentTypeHeaders = $response->getHeader('Content-Type');
148
		$contentType = array_shift($contentTypeHeaders);
149
		if ($contentType === 'text/xml;charset=UTF-8') {
150
			$xmlResponse = self::createXmlResponse($response);
151
			if ($xmlResponse->getErrorCode() !== 0) {
152
				throw new Fio\ServiceUnavailableException($xmlResponse->getError(), $xmlResponse->getErrorCode());
153
			}
154
		}
155
	}
156
157
	private static function sleep($filename)
158
	{
159
		$criticalTime = time() - filemtime($filename);
160
		if ($criticalTime < self::WAIT_TIME) {
161
			sleep(self::WAIT_TIME - $criticalTime);
162
		}
163
	}
164
165
	/**
166
	 * @param string $token
167
	 * @return string
168
	 */
169
	private function loadFileName($token)
170
	{
171
		$key = substr($token, 10, -10);
172
		if (!isset(self::$tokens[$key])) {
173
			self::$tokens[$key] = $this->tempDir . DIRECTORY_SEPARATOR . md5($key);
174
		}
175
176
		return self::$tokens[$key];
177
	}
178
179
	private static function safeProtocol($filename)
180
	{
181
		return Utils\SafeStream::PROTOCOL . '://' . $filename;
182
	}
183
184
	/**
185
	 * @param GuzzleHttp\Psr7\Response $response
186
	 * @return Pay\XMLResponse
187
	 */
188
	private static function createXmlResponse($response)
189
	{
190
		return new Pay\XMLResponse($response->getBody()->getContents());
191
	}
192
193
}
194