Completed
Push — master ( 471a2c...9baf90 )
by Alex
14s
created

Client::getPromise()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 18
ccs 11
cts 11
cp 1
rs 9.4285
cc 2
eloc 12
nc 1
nop 1
crap 2
1
<?php declare(strict_types=1);
2
/*
3
 * This file is part of the feed-io package.
4
 *
5
 * (c) Alexandre Debril <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace FeedIo\Async;
12
13
use \GuzzleHttp\ClientInterface;
14
use \GuzzleHttp\Promise\PromiseInterface;
15
use \FeedIo\Adapter\Guzzle\Response;
16
17
class Client
18
{
19
20
    /**
21
     * @var \GuzzleHttp\ClientInterface
22
     */
23
    protected $guzzleClient;
24
25
    /**
26
     * @var Reader
27
     */
28
    protected $reader;
29
30
    /**
31
     * Client constructor.
32
     * @param ClientInterface $guzzleClient
33
     * @param Reader $reader
34
     */
35 4
    public function __construct(ClientInterface $guzzleClient, Reader $reader)
36
    {
37 4
        $this->guzzleClient = $guzzleClient;
38 4
        $this->reader = $reader;
39 4
    }
40
41
    /**
42
     * @param iterable $requests
43
     * @return \Generator
44
     */
45 4
    public function getPromises(iterable $requests) : \Generator
46
    {
47 4
        foreach ($requests as $request) {
48 4
            yield $this->getPromise($request);
49
        }
50 4
    }
51
52
    /**
53
     * @param Request $request
54
     * @return PromiseInterface
55
     */
56 4
    protected function getPromise(Request $request) : PromiseInterface
57
    {
58 4
        $promise = $this->newPromise($request);
59 4
        $reader= $this->reader;
60
61 3
        $promise->then(function ($psrResponse) use ($request, $reader) {
62
            try {
63 3
                $request->setResponse(new Response($psrResponse));
64 3
                $reader->handle($request);
65 2
            } catch (\Exception $e) {
66 1
                $reader->handleError($request, $e);
67
            }
68
        }, function ($error) use ($request, $reader) {
69 1
            $reader->handleError($request, $error);
70 4
        });
71
72 4
        return $promise;
73
    }
74
75
    /**
76
     * @param Request $request
77
     * @return PromiseInterface
78
     */
79 4
    protected function newPromise(Request $request) : PromiseInterface
80
    {
81
        $options = [
82
            'headers' => [
83 4
                'User-Agent' => 'Mozilla/5.0 (X11; U; Linux i686; fr; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1',
84 4
                'If-Modified-Since' => $request->getModifiedSince()->format(\DateTime::RFC2822)
85
            ]
86
        ];
87
88 4
        return $this->guzzleClient->requestAsync('GET', $request->getUrl(), $options);
89
    }
90
}
91