Completed
Pull Request — master (#6)
by Arnold
07:00
created

Http::prepare()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace LegalThings\DataEnricher\Processor;
4
5
use LegalThings\DataEnricher;
6
use LegalThings\DataEnricher\Node;
7
use LegalThings\DataEnricher\Processor;
8
use GuzzleHttp\Client;
9
use GuzzleHttp\Promise;
10
use GuzzleHttp\Psr7\Response;
11
12
/**
13
 * Load an external source
14
 */
15
class Http implements Processor
16
{
17
    /**
18
     * Property key which should trigger the processor
19
     * @var string
20
     */
21
    protected $property;
22
    
23
    /**
24
     * @var \SplObjectStorage|Promise\PromiseInterface[]
25
     */
26
    protected $promises;
27
    
28
    /**
29
     * Class constructor
30
     * 
31
     * @param DataEnricher $invoker
32
     * @param string       $property  Property key with the processing instruction
33
     */
34
    public function __construct(DataEnricher $invoker, $property)
35
    {
36
        $this->property = $property;
37
    }
38
    
39
    /**
40
     * Get the property key that holds the processing instruction
41
     * 
42
     * @return string
43
     */
44
    public function getProperty()
45
    {
46
        return $this->property;
47
    }
48
    
49
    /**
50
     * Prepare processing to nodes
51
     * 
52
     * @param Node[] $nodes
53
     */
54
    public function prepare(array $nodes)
55
    {
56
        $this->promises = $this->request($nodes);
57
    }
58
    
59
    /**
60
     * Do async requests for each node
61
     * 
62
     * @param Node[] $nodes
63
     * @return \SplObjectStorage|Promise\PromiseInterface[]
64
     */
65
    protected function request($nodes)
66
    {
67
        $client = new Client();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
68
        $promises = new \SplObjectStorage();
69
        
70
        foreach ($nodes as $node) {
71
            if ($node->hasInstruction($this)) {
72
                $url = $node->getInstruction($this);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 13 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
73
                $promises[$node] = $client->getAsync($url);
74
            }
75
        }
76
        
77
        return $promises;
78
    }        
79
    
80
    /**
81
     * Apply results to a node
82
     * 
83
     * @param Node $node
84
     */
85
    public function applyToNode(Node $node)
86
    {
87
        if (!isset($this->promises[$node])) {
88
            return;
89
        }
90
        
91
        $result = null;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
92
        $response = $this->promises[$node]->wait();
93
94
        if ($this->hasExpectedResponse($response)) {
95
            $result = json_decode($response->body());
96
97
            if (!$result) {
98
                $url = $node->getInstruction($this);
99
                trigger_error("Failed to fetch '$url': Corrupt JSON response", E_USER_WARNING);
100
            }
101
        }
102
103
        $node->setResult($result);
104
    }
105
    
106
    /**
107
     * Check if we got an expected response
108
     * 
109
     * @param Response $response
110
     * @return boolean
111
     */
112
    protected function hasExpectedResponse(Response $response)
113
    {
114
        $status = $response->getStatusCode();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
115
        $contentType = preg_replace('/\s*;.*$/', '', $response->getHeader('content-type'));
116
        
117
        if ($status >= 300 || !in_array($contentType, ['application/json', 'text/plain'])) {
118
            $url = $node->getInstruction($this);
0 ignored issues
show
Bug introduced by
The variable $node does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
119
            
120
            if ($contentType === 'text/plain') {
121
                $message = $response->getBody();
122
            } else {
123
                $message = "Server responded with a $status status and $contentType";
124
            }
125
            
126
            trigger_error("Failed to fetch '$url': $message", E_USER_WARNING);
127
            return false;
128
        }
129
        
130
        return true;
131
    }
132
}
133