Completed
Pull Request — develop (#18)
by
unknown
05:23 queued 02:58
created

HttpClient::checkFileUploadRequest()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 40
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 40
ccs 0
cts 18
cp 0
rs 6.7272
cc 7
eloc 18
nc 8
nop 1
crap 56
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
    /** @var string */
22
    private $url;
23
24
    /**
25
     * Parse Body and if File is found it will find file and send it
26
     *
27
     * @param string $method  Request method to be used
28
     * @param string $uri     Url to where to send data
29
     * @param array  $options Config params
30
     *
31
     * @return \GuzzleHttp\Promise\PromiseInterface
32
     */
33
    public function requestAsync($method, $uri = null, array $options = [])
34
    {
35
        $this->url = $uri;
36
        $options = $this->checkFileUploadRequest($options);
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
        
54
        // Remove un-used param
55
        unset($options['origin']);
56
57
        // Is there a file and a @
58
        if (!isset($options['json'])
59
            || !isset($options['json']['file'])
60
            || !strpos($options['json']['file'], '@') == 0) {
61
            return $options;
62
        }
63
64
        // Find file
65
        $fileName = preg_replace('/([^\/]+$)/', substr($options['json']['file'], 1), $originFileName);
66
        $fileName = str_replace('//', '/', $fileName);
67
        if (!file_exists($fileName)) {
68
            return $options;
69
        }
70
71
        // File should only be sent as so.
72
        unset($options['json']['file']);
73
74
        // We send the data in URL
75
        $options['query'] = ['metadata' =>  json_encode($options['json'])];
76
77
        // Guzzle modify header if we send json.
78
        unset($options['json']);
79
80
        // We send file only
81
        $options['body'] = fopen($fileName, 'r');
82
83
        return $options;
84
85
    }
86
}
87