Completed
Pull Request — master (#5)
by Moesjarraf
08:07
created

Http   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 120
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 16
c 1
b 0
f 1
lcom 1
cbo 3
dl 0
loc 120
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getProperty() 0 4 1
A applyTo() 0 9 2
A request() 0 14 3
B applyResults() 0 22 5
A hasExpectedResponse() 0 20 4
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
     * Class constructor
25
     * 
26
     * @param DataEnricher $invoker
27
     * @param string       $property  Property key with the processing instruction
28
     */
29
    public function __construct(DataEnricher $invoker, $property)
30
    {
31
        $this->property = $property;
32
    }
33
    
34
    /**
35
     * Get the property key that holds the processing instruction
36
     * 
37
     * @return string
38
     */
39
    public function getProperty()
40
    {
41
        return $this->property;
42
    }
43
    
44
    /**
45
     * Apply processing to nodes
46
     * 
47
     * @param Node[] $nodes
48
     */
49
    public function applyTo(array $nodes)
50
    {
51
        $promises = $this->request($nodes);
52
        if (empty($promises)) {
53
            return;
54
        }
55
        
56
        $this->applyResults($promises);
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 nodes
82
     * 
83
     * @param \SplObjectStorage|Promise\PromiseInterface[] $promises
84
     */
85
    protected function applyResults($promises)
86
    {
87
        $results = new \SplObjectStorage();
88
        foreach ($promises as $node => $promise) {
89
            $results[$node] = $promise->wait();
90
        }
91
92
        foreach ($results as $node => $response) {
93
            $result = null;
94
            
95
            if ($this->hasExpectedResponse($response)) {
96
                $result = json_decode($response->body());
97
                
98
                if (!$result) {
99
                    $url = $node->getInstruction($this);
0 ignored issues
show
Bug introduced by
The method getInstruction cannot be called on $node (of type integer|string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
100
                    trigger_error("Failed to fetch '$url': Corrupt JSON response", E_USER_WARNING);
101
                }
102
            }
103
            
104
            $node->setResult($result);
0 ignored issues
show
Bug introduced by
The method setResult cannot be called on $node (of type integer|string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
105
        }
106
    }
107
    
108
    /**
109
     * Check if we got an expected response
110
     * 
111
     * @param Response $response
112
     * @return boolean
113
     */
114
    protected function hasExpectedResponse(Response $response)
115
    {
116
        $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...
117
        $contentType = preg_replace('/\s*;.*$/', '', $response->getHeader('content-type'));
118
        
119
        if ($status >= 300 || !in_array($contentType, ['application/json', 'text/plain'])) {
120
            $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...
121
            
122
            if ($contentType === 'text/plain') {
123
                $message = $response->getBody();
124
            } else {
125
                $message = "Server responded with a $status status and $contentType";
126
            }
127
            
128
            trigger_error("Failed to fetch '$url': $message", E_USER_WARNING);
129
            return false;
130
        }
131
        
132
        return true;
133
    }
134
}
135