Client::postJsonAsync()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 9
Ratio 100 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 3
dl 9
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of Jitamin.
5
 *
6
 * Copyright (C) Jitamin Team
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Jitamin\Foundation\Http;
13
14
use Jitamin\Bus\Job\HttpAsyncJob;
15
use Jitamin\Foundation\Base;
16
17
/**
18
 * HTTP client.
19
 */
20
class Client extends Base
21
{
22
    /**
23
     * HTTP connection timeout in seconds.
24
     *
25
     * @var int
26
     */
27
    const HTTP_TIMEOUT = 5;
28
29
    /**
30
     * Number of maximum redirections for the HTTP client.
31
     *
32
     * @var int
33
     */
34
    const HTTP_MAX_REDIRECTS = 2;
35
36
    /**
37
     * HTTP client user agent.
38
     *
39
     * @var string
40
     */
41
    const HTTP_USER_AGENT = 'Jitamin';
42
43
    /**
44
     * Send a GET HTTP request.
45
     *
46
     * @param string   $url
47
     * @param string[] $headers
48
     *
49
     * @return string
50
     */
51
    public function get($url, array $headers = [])
52
    {
53
        return $this->doRequest('GET', $url, '', $headers);
54
    }
55
56
    /**
57
     * Send a GET HTTP request and parse JSON response.
58
     *
59
     * @param string   $url
60
     * @param string[] $headers
61
     *
62
     * @return array
63
     */
64
    public function getJson($url, array $headers = [])
65
    {
66
        $response = $this->doRequest('GET', $url, '', array_merge(['Accept: application/json'], $headers));
67
68
        return json_decode($response, true) ?: [];
69
    }
70
71
    /**
72
     * Send a POST HTTP request encoded in JSON.
73
     *
74
     * @param string   $url
75
     * @param array    $data
76
     * @param string[] $headers
77
     *
78
     * @return string
79
     */
80
    public function postJson($url, array $data, array $headers = [])
81
    {
82
        return $this->doRequest(
83
            'POST',
84
            $url,
85
            json_encode($data),
86
            array_merge(['Content-type: application/json'], $headers)
87
        );
88
    }
89
90
    /**
91
     * Send a POST HTTP request encoded in JSON (Fire and forget).
92
     *
93
     * @param string   $url
94
     * @param array    $data
95
     * @param string[] $headers
96
     */
97 View Code Duplication
    public function postJsonAsync($url, array $data, array $headers = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
98
    {
99
        $this->queueManager->push(HttpAsyncJob::getInstance($this->container)->withParams(
0 ignored issues
show
Documentation introduced by
The property queueManager does not exist on object<Jitamin\Foundation\Http\Client>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
100
            'POST',
101
            $url,
102
            json_encode($data),
103
            array_merge(['Content-type: application/json'], $headers)
104
        ));
105
    }
106
107
    /**
108
     * Send a POST HTTP request encoded in www-form-urlencoded.
109
     *
110
     * @param string   $url
111
     * @param array    $data
112
     * @param string[] $headers
113
     *
114
     * @return string
115
     */
116
    public function postForm($url, array $data, array $headers = [])
117
    {
118
        return $this->doRequest(
119
            'POST',
120
            $url,
121
            http_build_query($data),
122
            array_merge(['Content-type: application/x-www-form-urlencoded'], $headers)
123
        );
124
    }
125
126
    /**
127
     * Send a POST HTTP request encoded in www-form-urlencoded (fire and forget).
128
     *
129
     * @param string   $url
130
     * @param array    $data
131
     * @param string[] $headers
132
     */
133 View Code Duplication
    public function postFormAsync($url, array $data, array $headers = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
134
    {
135
        $this->queueManager->push(HttpAsyncJob::getInstance($this->container)->withParams(
0 ignored issues
show
Documentation introduced by
The property queueManager does not exist on object<Jitamin\Foundation\Http\Client>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
136
            'POST',
137
            $url,
138
            http_build_query($data),
139
            array_merge(['Content-type: application/x-www-form-urlencoded'], $headers)
140
        ));
141
    }
142
143
    /**
144
     * Make the HTTP request.
145
     *
146
     * @param string   $method
147
     * @param string   $url
148
     * @param string   $content
149
     * @param string[] $headers
150
     *
151
     * @return string
152
     */
153
    public function doRequest($method, $url, $content, array $headers)
154
    {
155
        if (empty($url)) {
156
            return '';
157
        }
158
159
        $startTime = microtime(true);
160
        $stream = @fopen(trim($url), 'r', false, stream_context_create($this->getContext($method, $content, $headers)));
161
        $response = '';
162
163
        if (is_resource($stream)) {
164
            $response = stream_get_contents($stream);
165
        } else {
166
            $this->logger->error('HttpClient: request failed');
0 ignored issues
show
Documentation introduced by
The property logger does not exist on object<Jitamin\Foundation\Http\Client>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
167
        }
168
169
        if (DEBUG) {
170
            $this->logger->debug('HttpClient: url='.$url);
0 ignored issues
show
Documentation introduced by
The property logger does not exist on object<Jitamin\Foundation\Http\Client>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
171
            $this->logger->debug('HttpClient: headers='.var_export($headers, true));
0 ignored issues
show
Documentation introduced by
The property logger does not exist on object<Jitamin\Foundation\Http\Client>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
172
            $this->logger->debug('HttpClient: payload='.$content);
0 ignored issues
show
Documentation introduced by
The property logger does not exist on object<Jitamin\Foundation\Http\Client>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
173
            $this->logger->debug('HttpClient: metadata='.var_export(@stream_get_meta_data($stream), true));
0 ignored issues
show
Documentation introduced by
The property logger does not exist on object<Jitamin\Foundation\Http\Client>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
174
            $this->logger->debug('HttpClient: response='.$response);
0 ignored issues
show
Documentation introduced by
The property logger does not exist on object<Jitamin\Foundation\Http\Client>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
175
            $this->logger->debug('HttpClient: executionTime='.(microtime(true) - $startTime));
0 ignored issues
show
Documentation introduced by
The property logger does not exist on object<Jitamin\Foundation\Http\Client>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
176
        }
177
178
        return $response;
179
    }
180
181
    /**
182
     * Get stream context.
183
     *
184
     * @param string   $method
185
     * @param string   $content
186
     * @param string[] $headers
187
     *
188
     * @return array
189
     */
190
    private function getContext($method, $content, array $headers)
191
    {
192
        $default_headers = [
193
            'User-Agent: '.self::HTTP_USER_AGENT,
194
            'Connection: close',
195
        ];
196
197
        if (HTTP_PROXY_USERNAME) {
198
            $default_headers[] = 'Proxy-Authorization: Basic '.base64_encode(HTTP_PROXY_USERNAME.':'.HTTP_PROXY_PASSWORD);
199
        }
200
201
        $headers = array_merge($default_headers, $headers);
202
203
        $context = [
204
            'http' => [
205
                'method'           => $method,
206
                'protocol_version' => 1.1,
207
                'timeout'          => self::HTTP_TIMEOUT,
208
                'max_redirects'    => self::HTTP_MAX_REDIRECTS,
209
                'header'           => implode("\r\n", $headers),
210
                'content'          => $content,
211
            ],
212
        ];
213
214
        if (HTTP_PROXY_HOSTNAME) {
215
            $context['http']['proxy'] = 'tcp://'.HTTP_PROXY_HOSTNAME.':'.HTTP_PROXY_PORT;
216
            $context['http']['request_fulluri'] = true;
217
        }
218
219 View Code Duplication
        if (HTTP_VERIFY_SSL_CERTIFICATE === false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
220
            $context['ssl'] = [
221
                'verify_peer'       => false,
222
                'verify_peer_name'  => false,
223
                'allow_self_signed' => true,
224
            ];
225
        }
226
227
        return $context;
228
    }
229
}
230