Completed
Push — master ( 5c8da7...549922 )
by Stefano
04:39
created

HTTP   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 124
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 124
rs 10
wmc 27
lcom 1
cbo 2

11 Methods

Rating   Name   Duplication   Size   Complexity  
C request() 0 54 12
A useJSON() 0 3 2
A addHeader() 0 3 1
A removeHeader() 0 3 1
A headers() 0 6 3
A userAgent() 0 3 2
A get() 0 3 1
A post() 0 3 1
A put() 0 3 1
A delete() 0 3 1
A info() 0 20 2
1
<?php
2
3
/**
4
 * HTTP
5
 *
6
 * cURL proxy.
7
 *
8
 * @package core
9
 * @author [email protected]
10
 * @copyright Caffeina srl - 2015 - http://caffeina.it
11
 */
12
13
class HTTP {
0 ignored issues
show
Coding Style introduced by
The property $json_data is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $last_info is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
14
  use Module, Events;
15
16
  protected static $UA          = "Mozilla/4.0 (compatible; Core::HTTP; Windows NT 6.1)",
0 ignored issues
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
17
                   $json_data   = false,
18
                   $headers     = [],
19
                   $last_info   = null;
20
21
  protected static function request($method, $url, $data=[], array $headers=[], $data_as_json=false, $username=null, $password = null){
22
    $http_method = strtoupper($method);
23
    $ch  = curl_init($url);
24
    $opt = [
25
      CURLOPT_CUSTOMREQUEST   => $http_method,
26
      CURLOPT_SSL_VERIFYHOST  => false,
27
      CURLOPT_CONNECTTIMEOUT  => 10,
28
      CURLOPT_RETURNTRANSFER  => true,
29
      CURLOPT_USERAGENT       => static::$UA,
30
      CURLOPT_HEADER          => false,
31
      CURLOPT_MAXREDIRS       => 10,
32
      CURLOPT_FOLLOWLOCATION  => true,
33
      CURLOPT_ENCODING        => '',
34
    ];
35
36
    if($username && $password) {
37
      $opt[CURLOPT_USERPWD] = "$username:$password";
38
    }
39
40
    $headers = array_merge($headers,static::$headers);
41
42
    if($http_method == 'GET'){
43
        if($data && is_array($data)){
44
          $tmp                       = [];
45
          $queried_url               = $url;
46
          foreach($data as $key=>$val) $tmp[] = $key.'='.$val;
47
          $queried_url               .= (strpos($queried_url,'?') === false) ? '?' : '&';
48
          $queried_url               .= implode('&',$tmp);
49
          $opt[CURLOPT_URL]          = $queried_url;
50
          $opt[CURLOPT_HTTPGET]      = true;
51
          unset($opt[CURLOPT_CUSTOMREQUEST]);
52
        }
53
    } else {
54
        $opt[CURLOPT_CUSTOMREQUEST]  = $http_method;
55
        if($data_as_json or is_object($data)){
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
56
          $headers['Content-Type']   = 'application/json';
57
          $opt[CURLOPT_POSTFIELDS]   = json_encode($data);
58
        } else {
59
          $opt[CURLOPT_POSTFIELDS]   = http_build_query($data);
60
        }
61
    }
62
63
    curl_setopt_array($ch,$opt);
64
    $_harr = [];
65
    foreach($headers as $key=>$val)  $_harr[] = $key.': '.$val;
66
    curl_setopt($ch, CURLOPT_HTTPHEADER, $_harr);
67
    $result = curl_exec($ch);
68
    $contentType = strtolower(curl_getinfo($ch, CURLINFO_CONTENT_TYPE));
69
    static::$last_info = curl_getinfo($ch);
70
    if(false !== strpos($contentType,'json')) $result = json_decode($result);
71
    curl_close($ch);
72
    static::trigger("request", $result, static::$last_info);
73
    return $result;
74
  }
75
76
  public static function useJSON($value=null){
77
    return $value===null ? static::$json_data : static::$json_data = $value;
78
  }
79
80
  public static function addHeader($name,$value){
81
    static::$headers[$name] = $value;
82
  }
83
84
  public static function removeHeader($name){
85
    unset(static::$headers[$name]);
86
  }
87
88
  public static function headers($name=null){
89
    // null === $name ?? static::$headers ?? static::$headers[$name]
90
    return null === $name
91
           ? static::$headers
92
           : ( isset(static::$headers[$name]) ? static::$headers[$name] : '' );
93
  }
94
95
  public static function userAgent($value=null){
96
    return $value===null ? static::$UA : static::$UA = $value;
97
  }
98
99
  public static function get($url, $data=null, array $headers=[], $username = null, $password = null){
100
    return static::request('get',$url,$data,$headers,false,$username,$password);
101
  }
102
103
  public static function post($url, $data=null, array $headers=[], $username = null, $password = null){
104
    return static::request('post',$url,$data,$headers,static::$json_data,$username,$password);
105
  }
106
107
  public static function put($url, $data=null, array $headers=[], $username = null, $password = null){
108
    return static::request('put',$url,$data,$headers,static::$json_data,$username,$password);
109
  }
110
111
  public static function delete($url, $data=null, array $headers=[], $username = null, $password = null){
112
    return static::request('delete',$url,$data,$headers,static::$json_data,$username,$password);
113
  }
114
115
  public static function info($url = null){
116
    if ($url){
117
      curl_setopt_array($ch = curl_init($url), [
118
        CURLOPT_SSL_VERIFYHOST  => false,
119
        CURLOPT_CONNECTTIMEOUT  => 10,
120
        CURLOPT_RETURNTRANSFER  => true,
121
        CURLOPT_USERAGENT       => static::$UA,
122
        CURLOPT_HEADER          => false,
123
        CURLOPT_ENCODING        => '',
124
        CURLOPT_FILETIME        => true,
125
        CURLOPT_NOBODY          => true,
126
      ]);
127
      curl_exec($ch);
128
      $info = curl_getinfo($ch);
129
      curl_close($ch);
130
      return $info;
131
    } else {
132
      return static::$last_info;
133
    }
134
  }
135
136
}
137
138
class HTTP_Request {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
Coding Style introduced by
This class is not in CamelCase format.

Classes in PHP are usually named in CamelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. The whole name starts with a capital letter as well.

Thus the name database provider becomes DatabaseProvider.

Loading history...
139
  public $method   = 'GET',
0 ignored issues
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
140
         $url      = '',
141
         $headers  = [],
142
         $body     = '';
143
144
  public function __construct($method, $url, $headers=[], $data=null){
0 ignored issues
show
Unused Code introduced by
The parameter $url is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
145
    $this->method   = strtoupper($method);
146
    $this->url      = new URL($this->url);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \URL($this->url) of type object<URL> is incompatible with the declared type string of property $url.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
147
    $this->headers  = (array)$headers;
148
    if ($data) {
149
      if (isset($this->headers["Content-Type"]) && $this->headers["Content-Type"]=='application/json')
150
        $this->body = json_encode($data);
151
      else
152
        $this->body = http_build_query($data);
153
    }
154
  }
155
156
  public function __toString(){
157
    return "$this->method {$this->url->path}{$this->url->query} HTTP/1.1\r\n"
158
          ."Host: {$this->url->host}\r\n"
159
          .($this->headers ? implode("\r\n",$this->headers) . "\r\n" : '')
160
          ."\r\n{$this->body}";
161
  }
162
}
163
164
165
class HTTP_Response {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
Coding Style introduced by
This class is not in CamelCase format.

Classes in PHP are usually named in CamelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. The whole name starts with a capital letter as well.

Thus the name database provider becomes DatabaseProvider.

Loading history...
166
  public $status   = 200,
0 ignored issues
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
167
         $headers  = [],
168
         $contents = '';
169
170
  public function __construct($contents, $status, $headers){
171
    $this->status   = $status;
172
    $this->contents = $contents;
173
    $this->headers  = (array)$headers;
174
  }
175
176
  public function __toString(){
177
    return $this->content;
0 ignored issues
show
Bug introduced by
The property content does not seem to exist. Did you mean contents?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
178
  }
179
}
180
181