retailCRM PHP API client
  • Namespace
  • Class
  • Tree
  • Deprecated
  • Todo

Namespaces

  • RetailCrm
    • Exception
    • Http
    • Response

Classes

  • Client
 1 <?php
 2 
 3 namespace RetailCrm\Http;
 4 
 5 use RetailCrm\Exception\CurlException;
 6 use RetailCrm\Response\ApiResponse;
 7 
 8 /**
 9  * HTTP client
10  */
11 class Client
12 {
13     const METHOD_GET = 'GET';
14     const METHOD_POST = 'POST';
15 
16     protected $url;
17     protected $defaultParameters;
18 
19     public function __construct($url, array $defaultParameters = array())
20     {
21         if (false === stripos($url, 'https://')) {
22             throw new \InvalidArgumentException('API schema requires HTTPS protocol');
23         }
24 
25         $this->url = $url;
26         $this->defaultParameters = $defaultParameters;
27     }
28 
29     /**
30      * Make HTTP request
31      *
32      * @param string $path
33      * @param string $method (default: 'GET')
34      * @param array $parameters (default: array())
35      * @param int $timeout
36      * @return ApiResponse
37      */
38     public function makeRequest($path, $method, array $parameters = array(), $timeout = 30)
39     {
40         $allowedMethods = array(self::METHOD_GET, self::METHOD_POST);
41         if (!in_array($method, $allowedMethods)) {
42             throw new \InvalidArgumentException(sprintf(
43                 'Method "%s" is not valid. Allowed methods are %s',
44                 $method,
45                 implode(', ', $allowedMethods)
46             ));
47         }
48 
49         $parameters = array_merge($this->defaultParameters, $parameters);
50 
51         $path = $this->url . $path;
52         if (self::METHOD_GET === $method && sizeof($parameters)) {
53             $path .= '?' . http_build_query($parameters);
54         }
55 
56         $ch = curl_init();
57         curl_setopt($ch, CURLOPT_URL, $path);
58         curl_setopt($ch, CURLOPT_FAILONERROR, false);
59         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return into a variable
60         curl_setopt($ch, CURLOPT_TIMEOUT, (int) $timeout); // times out after 30s
61         // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
62         // curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
63 
64         if (self::METHOD_POST === $method) {
65             curl_setopt($ch, CURLOPT_POST, true);
66             curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
67         }
68 
69         $responseBody = curl_exec($ch);
70         $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
71 
72         $errno = curl_errno($ch);
73         $error = curl_error($ch);
74         curl_close($ch);
75 
76         if ($errno) {
77             throw new CurlException($error, $errno);
78         }
79 
80         return new ApiResponse($statusCode, $responseBody);
81     }
82 }
83 
retailCRM PHP API client API documentation generated by ApiGen