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

HttpClient::checkFileUploadRequest()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 35
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 35
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
        // 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
71
        // We send the data in URL
72
        $this->url .= '?metadata='.json_encode($options['json']);
73
        unset($options['json']);
74
75
        // We send file only
76
        $options['body'] = fopen($fileName, 'r');
77
78
        return $options;
79
80
    }
81
}
82