Completed
Push — feature/EVO-3237-send-file ( 1142db )
by
unknown
03:04
created

HttpClient::request()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 0
cts 6
cp 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 3
crap 2
1
<?php
2
3
namespace Graviton\ImportExport\Service;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Psr7;
7
8
9
/**
10
 * Class HttpClient
11
 * Extends Guzzle client
12
 *
13
 * @package Graviton\ImportExport\Service
14
 */
15
class HttpClient extends Client
16
{
17
    /**
18
     * Parse Body and if File is found it will find file and send it
19
     * On request error, Curl error it will attempt again after sleep 0.5s
20
     *
21
     * @inheritdoc
22
     *
23
     * @param string $method
24
     * @param null $uri
25
     * @param array $options
26
     * @return \GuzzleHttp\Promise\PromiseInterface
27
     */
28
    public function requestAsync($method, $uri = null, array $options = [])
29
    {
30
        $options = $this->checkFileUploadRequest($options);
31
32
        return parent::requestAsync($method, $uri, $options);
33
    }
34
35
    /**
36
     * Parse Body and if File is found it will find file and send it
37
     * On request error, Curl error it will attempt again after sleep 0.5s
38
     *
39
     * @inheritdoc
40
     *
41
     * @param string $method
42
     * @param null $uri
43
     * @param array $options
44
     * @return mixed
45
     */
46
    public function request($method, $uri = null, array $options = [])
47
    {
48
        $options = $this->checkFileUploadRequest($options);
49
        $options[RequestOptions::SYNCHRONOUS] = true;
50
        return $this->requestAsync($method, $uri, $options)->wait();
51
    }
52
53
    /**
54
     * @param array $options Curl data options
55
     * @return array options
56
     */
57
    private function checkFileUploadRequest($options)
58
    {
59
        $originFileName = array_key_exists('origin', $options) ? $options['origin'] : false;
60
61
        if (!$originFileName) {
62
            return $options;
63
        }
64
        // Remove un-used param
65
        unset($options['origin']);
66
67
        // Is there a file and a @
68
        if (!isset($options['json'], $options['json']['file']) && strpos($options['json']['file'], '@') == 0) {
69
            return $options;
70
        }
71
72
        // Find file
73
        $fileName = preg_replace('/([^\/]+$)/', substr($options['json']['file'], 1), $originFileName);
74
        if (!file_exists($fileName)) {
75
            return $options;
76
        }
77
        
78
        // We send file only
79
        $options = [];
80
        $options['body'] = fopen(str_replace('//', '/', $fileName), 'r');
81
82
        return $options;
83
84
    }
85
}