Issues (22)

DAO/Connection.php (9 issues)

1
<?php
2
3
namespace GeodisBundle\DAO;
4
5
use Doctrine\ORM\EntityManager;
0 ignored issues
show
The type Doctrine\ORM\EntityManager was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use GeodisBundle\DAO\Exception\ApiException;
7
use GuzzleHttp\Client;
8
use GuzzleHttp\Psr7;
9
use GuzzleHttp\Psr7\Request;
10
use GuzzleHttp\Psr7\Response;
11
12
class Connection
13
{
14
    const CONTENT_TYPE_JSON = 'application/json';
15
16
    private static $baseUrl;
17
    private static $serviceRecordSend;
18
    private static $serviceValidationSend;
19
20
    private static $clientId;
21
    private static $clientSecret;
22
23
    private static $em;
24
    private static $contentType = self::CONTENT_TYPE_JSON;
25
26
    public static function setConfig(array $config, EntityManager $em)
27
    {
28
        self::$em = $em;
29
        self::$baseUrl = $config['baseUrl'];
30
        self::$serviceRecordSend = $config['serviceRecordSend'];
31
        self::$serviceValidationSend = $config['serviceValidationSend'];
32
33
        self::$clientId = $config['clientId'];
34
        self::$clientSecret = $config['clientSecret'];
35
    }
36
37
    /**
38
     * Create Request.
39
     *
40
     * @return GuzzleHttp\Psr7\Request;
0 ignored issues
show
The type GeodisBundle\DAO\GuzzleHttp\Psr7\Request was not found. Did you mean GuzzleHttp\Psr7\Request? If so, make sure to prefix the type with \.
Loading history...
41
     */
42
    private static function createRequest($method = 'GET', $endpoint, $body, $serviceCalled)
43
    {
44
        /*
45
            X-GEODIS-Service:
46
            id;current timestamp in ms;language;hash
47
                Id => My Space login
48
                CurrentTimestamp => Timestamp when you created the call. Epoch format in  millisecondes
49
                Language => Language expected
50
                Hash => Message hashe sha256
51
                        Message sent, to call one of the methods of the service must be the subject of a calculation of its hash sha256.
52
                        This calculation is based on the following parameter :
53
                        Api key;id;current timestamp in ms;language;service;json query parameter
54
                            API Key => API  key in My Space
55
                            Id => My Space login
56
                            Current Timestamp => Timestamp when you created the call. Epoch format in  millisecondes
57
                            Language => Langue expected
58
                            Service => Service call
59
                            Json query parameter => The parameters call, JSON format
60
61
            Example =>
62
            X-GEODIS-Service:
63
            ZANGRA;1584105904250;fr;64c34a8d118f81f9c72682779cac98501d860cc1e2eb76456887b105aaa5b3cd
64
        */
65
        $now = new \DateTime('now');
66
        $now = $now->getTimestamp() * 1000;
67
68
        if ('enregistrement' == $serviceCalled) {
69
            $serviceCalled = self::$serviceRecordSend;
70
        } else {
71
            $serviceCalled = self::$serviceValidationSend;
72
        }
73
74
        $hash = self::$clientSecret.';'.self::$clientId.';'.$now.';fr;'.$serviceCalled.';'.$body;
75
76
        $hash = hash('sha256', $hash);
77
78
        $header = array('X-GEODIS-Service' => self::$clientId.';'.$now.';fr;'.$hash);
79
80
        $request = new Request($method, $endpoint, $header, $body);
81
82
        return  $request;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $request returns the type GuzzleHttp\Psr7\Request which is incompatible with the documented return type GeodisBundle\DAO\GuzzleHttp\Psr7\Request.
Loading history...
83
    }
84
85
    /**
86
     * Execute request.
87
     *
88
     * @param string $method
89
     * @param string $json
90
     * @param string $url
91
     *
92
     * @return array
93
     */
94
    public static function Request($method, $service, $body = null)
95
    {
96
        //$url = self::$baseUrl;
97
        if ('enregistrement' == $service) {
98
            $url = self::$baseUrl.'/'.self::$serviceRecordSend;
99
        } else {
100
            $url = self::$baseUrl.'/'.self::$serviceValidationSend;
101
        }
102
103
        try {
104
            $client = new Client();
105
            $request = self::createRequest($method, $url, $body, $service);
106
            $response = $client->send($request);
107
        } catch (\Exception $ex) {
108
            $error = $ex->getResponse()->getBody()->getContents();
0 ignored issues
show
The method getResponse() does not exist on Exception. It seems like you code against a sub-type of Exception such as GuzzleHttp\Exception\RequestException. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

108
            $error = $ex->/** @scrutinizer ignore-call */ getResponse()->getBody()->getContents();
Loading history...
The assignment to $error is dead and can be removed.
Loading history...
109
110
            throw new ApiException($ex->getMessage(), $ex->getResponse()->getStatusCode());
111
        }
112
113
        try {
114
            $parsedResponse = self::parseResponse($response, $request->getMethod());
115
116
            return $parsedResponse;
117
        } catch (\Exception $ex) {
118
            throw new ApiException($e->getMessage(), $e->getStatusCode());
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $e seems to be never defined.
Loading history...
119
        }
120
    }
121
122
    private static function parseResponse(Response $response, $method, $returnSingleIfPossible = true)
123
    {
124
        if (204 === $response->getStatusCode() && 'POST' == $method) {
125
            throw new ApiException($response->getReasonPhrase(), $response->getStatusCode());
126
        }
127
128
        if (self::CONTENT_TYPE_JSON === self::$contentType) {
129
            return self::parseJSON($response, $returnSingleIfPossible);
130
        }
131
132
        throw new ApiException($response->getReasonPhrase(), $response->getStatusCode());
133
    }
134
135
    /**
136
     * Parse JSON response.
137
     *
138
     * @param Response $response
139
     * @param bool     $returnSingleIfPossible
140
     *
141
     * @return array (associative)
142
     */
143
    private static function parseJSON(Response $response, $returnSingleIfPossible = true)
144
    {
145
        try {
146
            Psr7\rewind_body($response);
0 ignored issues
show
The function rewind_body was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

146
            /** @scrutinizer ignore-call */ 
147
            Psr7\rewind_body($response);
Loading history...
147
            $json = json_decode($response->getBody()->getContents(), true);
148
149
            if (is_array($json)) {
150
                if (array_key_exists('d', $json)) {
151
                    if (array_key_exists('results', $json['d'])) {
152
                        if ($returnSingleIfPossible && 1 == count($json['d']['results'])) {
153
                            return $json['d']['results'][0];
154
                        }
155
156
                        return $json['d']['results'];
157
                    }
158
159
                    return $json['d'];
160
                }
161
            }
162
163
            return $json;
164
        } catch (\ApiException $e) {
0 ignored issues
show
The type ApiException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
165
            throw new ApiException($e->getMessage(), $e->getStatusCode());
166
        }
167
    }
168
169
    public static function setContentType($type = 'json')
170
    {
171
        if ('xml' === $type) {
172
            self::$contentType = self::CONTENT_TYPE_XML;
0 ignored issues
show
The constant GeodisBundle\DAO\Connection::CONTENT_TYPE_XML was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
173
        }
174
175
        if ('json' === $type) {
176
            self::$contentType = self::CONTENT_TYPE_JSON;
177
        }
178
    }
179
}
180