Completed
Pull Request — develop (#18)
by
unknown
06:23 queued 03:13
created

HttpClient   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 8
c 2
b 0
f 0
lcom 1
cbo 1
dl 0
loc 65
ccs 0
cts 23
cp 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A requestAsync() 0 8 1
C checkFileUploadRequest() 0 37 7
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