Completed
Pull Request — development (#2700)
by
unknown
02:53
created

Tools::getApiType()   C

Complexity

Conditions 14
Paths 14

Size

Total Lines 31
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 210

Importance

Changes 0
Metric Value
dl 0
loc 31
ccs 0
cts 31
cp 0
rs 5.0864
c 0
b 0
f 0
cc 14
eloc 29
nc 14
nop 1
crap 210

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 9 and the first side effect is on line 2.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
$defflip = (!cfip()) ? exit(header('HTTP/1.1 401 Unauthorized')) : 1;
3
4
/**
5
 * Helper class for our cronjobs
6
 * Implements some common cron tasks outside
7
 * the scope of our web application
8
 **/
9
class Tools extends Base {
0 ignored issues
show
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...
10
  public function getOnlineVersions() {
11
    // Fetch version online, cache for a bit
12
    $key = $this->config['memcache']['keyprefix'] . 'ONLINE_VERSIONS';
0 ignored issues
show
Bug introduced by
The property config does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
13
    if (! $mpos_versions = $this->memcache->get($key)) {
14
      $url = $this->config['version_url'];
15
      $curl = curl_init();
16
      curl_setopt($curl, CURLOPT_URL, $url);
17
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
18
      curl_setopt($curl, CURLOPT_HEADER, false);
19
      $data = curl_exec($curl);
20
      preg_match('/define\(\'MPOS_VERSION\', \'(.*)\'\);/', $data, $match);
21
      $mpos_versions['MPOS_VERSION'] = @$match[1];
22
      preg_match('/define\(\'DB_VERSION\', \'(.*)\'\);/', $data, $match);
23
      $mpos_versions['DB_VERSION'] = @$match[1];
24
      preg_match('/define\(\'CONFIG_VERSION\', \'(.*)\'\);/', $data, $match);
25
      $mpos_versions['CONFIG_VERSION'] = @$match[1];
26
      curl_close($curl);
27
      return $this->memcache->setCache($key, $mpos_versions, 30);
0 ignored issues
show
Bug introduced by
The property memcache does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
28
    } else {
29
      return $mpos_versions;
30
    }
31
  }
32
  /**
33
   * Fetch JSON data from an API
34
   * @param url string API URL
35
   * @param target string API method
36
   * @param auth array Optional authentication data to be sent with
37
   * @return dec array JSON decoded PHP array
38
   **/
39
  public function getApi($url, $target, $auth=NULL) {
0 ignored issues
show
Unused Code introduced by
The parameter $auth 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...
40
    static $ch = null;
41
    static $ch = null;
42
    if (is_null($ch)) {
43
      $ch = curl_init();
44
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
45
      curl_setopt($ch, CURLOPT_TIMEOUT, 30);
46
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
47
      curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; PHP client; '.php_uname('s').'; PHP/'.phpversion().')');
48
    }
49
    curl_setopt($ch, CURLOPT_URL, $url . $target);
50
    // curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
51
52
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
53
54
    // run the query
55
    $res = curl_exec($ch);
56
    if ($res === false) {
57
      $this->setErrorMessage('Could not get reply: '.curl_error($ch));
58
      return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Tools::getApi of type dec.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
59
    }
60
    $dec = json_decode($res, true);
61
    if (!$dec) {
62
      $this->setErrorMessage('Invalid data received, please make sure connection is working and requested API exists');
63
      return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Tools::getApi of type dec.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
64
    }
65
    return $dec;
66
  }
67
68
  /**
69
   * Detect the API to properly extract information
70
   * @param url string API URL
71
   * @return data string API type
72
   **/
73
  private function getApiType($url) {
74
    if (preg_match('/coinchoose.com/', $url)) {
75
      return 'coinchoose';
76
    } else if (preg_match('/btc-e.nz/', $url)) {
77
      return 'btce';
78
    } else if (preg_match('/cryptopia.co.nz/', $url)) {
79
     return 'cryptopia';
80
    } else if (preg_match('/cryptorush.in/', $url)) {
81
      return 'cryptorush';
82
    } else if (preg_match('/mintpal.com/', $url)) {
83
      return 'mintpal';
84
    } else if (preg_match('/c-cex.com/', $url)) {
85
      return 'c-cex';
86
    } else if (preg_match('/bittrex.com/', $url)) {
87
      return 'bittrex';
88
    } else if (preg_match('/crypto-bridge.org/', $url)) {
89
      return 'cryptobridge';
90
    } else if (preg_match('/yobit.net/', $url)) {
91
      return 'yobit';
92
    } else if (preg_match('/binance.com/', $url)) {
93
      return 'binance';
94
    } else if (preg_match('/southxchange.com/', $url)) {
95
      return 'southxchange';
96
    } else if (preg_match('/mercatox.com/', $url)) {
97
      return 'mercatox';
98
    } else if (preg_match('/tradeogre.com/', $url)) {
99
      return 'tradeogre';
100
    }
101
    $this->setErrorMessage("API URL unknown");
102
    return false;
103
  }
104
105
  /**
106
   * Extract price information from API data
107
   **/
108
  public function getPrice() {
109
    $aData = $this->getApi($this->config['price']['url'], $this->config['price']['target']);
110
    $strBase = $this->config['currency'];
111
    $strQuote = $this->config['price']['currency'];
112
    // Check the API type for configured URL
113
    if (!$strApiType = $this->getApiType($this->config['price']['url']))
114
      return false;
115
    // if api data is valid, extract price depending on API type
116
    if (is_array($aData)) {
117
      switch ($strApiType) {
118
      	case 'coinchoose':
119
      	  foreach ($aData as $aItem) {
120
      	    if($strBase == $aItem[0])
121
      	      return $aItem['price'];
122
      	  }
123
      	  break;
124
      	case 'btce':
125
      	  return $aData['ticker']['last'];
126
      	  break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
127
        case 'cryptopia':
128
      	  return @$aData['Data']['LastPrice'];
129
      	  break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
130
      	case 'cryptorush':
131
      	  return @$aData["{$strBase}/{$strQuote}"]['last_trade'];
132
      	  break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
133
      	case 'mintpal':
134
      	  return @$aData['0']['last_price'];
135
      	  break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
136
        case 'c-cex':
137
          return @$aData['ticker']['lastprice'];
138
          break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
139
      	case 'bittrex':
140
      	  return @$aData['result']['Last'];
141
      	  break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
142
        case 'cryptobridge':
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
143
          foreach ($aData as $aItem) {
144
            if("{$strBase}_{$strQuote}" == $aItem['id'])
145
              return $aItem['last'];
146
          }
147
        case 'yobit':
148
          return @$aData[strtolower($strBase) . "_" . strtolower($strQuote)]['last'];
149
          break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
150
        case 'binance':
151
          return @$aData['price'];
152
          break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
153
        case 'southxchange':
154
          return @$aData['Last'];
155
          break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
156
        case 'mercatox':
157
          return @$aData["{$strBase}_{$strQuote}"]['last'];
158
          break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
159
        case 'tradeogre':
160
          return @$aData['price'];
161
          break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
162
      }
163
    } else {
164
      $this->setErrorMessage("Got an invalid response from ticker API");
165
      return false;
166
    }
167
    // Catchall, we have no data extractor for this API url
168
    $this->setErrorMessage("Undefined API to getPrice() on URL " . $this->config['price']['url']);
169
    return false;
170
  }
171
}
172
173
$tools = new Tools();
174
$tools->setDebug($debug);
175
$tools->setConfig($config);
176
$tools->setMemcache($memcache);
177