Completed
Push — feature/EVO-3237-send-file ( dbe8b4...d92d95 )
by
unknown
03:12
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 4
cp 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 3
crap 2
1
<?php
2
/**
3
 * Extending GuzzleHttp client
4
 */
5
namespace Graviton\ImportExport\Service;
6
7
use GuzzleHttp\Client;
8
use GuzzleHttp\Psr7;
9
use GuzzleHttp\Promise;
10
11
/**
12
 * Class HttpClient
13
 * Extends Guzzle client
14
 *
15
 * @author   List of contributors <https://github.com/libgraviton/import-export/graphs/contributors>
16
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
17
 * @link     http://swisscom.ch
18
 */
19
class HttpClient extends Client
20
{
21
    private $url;
22
23
    /**
24
     * Parse Body and if File is found it will find file and send it
25
     *
26
     * @param string $method  Request method to be used
27
     * @param string $uri     Url to where to send data
28
     * @param array  $options Config params
29
     *
30
     * @return \GuzzleHttp\Promise\PromiseInterface
31
     */
32
    public function requestAsync($method, $uri = null, array $options = [])
33
    {
34
        $this->url = $uri;
35
        $options = $this->checkFileUploadRequest($options);
36
37
38
        return parent::requestAsync($method, $this->url, $options);
39
    }
40
    
41
42
    /**
43
     * @param array $options Curl data options
44
     * @return array options
45
     */
46
    private function checkFileUploadRequest($options)
47
    {
48
        $originFileName = array_key_exists('origin', $options) ? $options['origin'] : false;
49
50
        if (!$originFileName) {
51
            return $options;
52
        }
53
        // Remove un-used param
54
        unset($options['origin']);
55
56
        // Is there a file and a @
57
        if (!isset($options['json'])
58
            || !isset($options['json']['file'])
59
            || !strpos($options['json']['file'], '@') == 0) {
60
            return $options;
61
        }
62
63
        // Find file
64
        $fileName = preg_replace('/([^\/]+$)/', substr($options['json']['file'], 1), $originFileName);
65
        $fileName = str_replace('//', '/', $fileName);
66
        if (!file_exists($fileName)) {
67
            return $options;
68
        }
69
        unset($options['json']['file']);
70
        unset($options['json']['id']);
71
72
        // We send the data in URL
73
        $this->url .= '?metadata='.json_encode($options['json']);
74
75
        // We send file only
76
        $options = [
77
            'body' => fopen($fileName, 'r')
78
        ];
79
80
        return $options;
81
82
    }
83
}
84