Bitly::getStatsArray()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 9
Ratio 100 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 9
loc 9
rs 9.9666
c 0
b 0
f 0
1
<?php
2
/*
3
Author: Ruslanas B.
4
http://bitly.googlecode.com
5
6
Usage:
7
$bitly = new Bitly($login, $apiKey);
8
$short = $bitly->shortenSingle('http://bitly.googlecode.com');
9
$long = $bitly->expandSingle($short);
10
print_r( $bitly->getStatsArray($short));
11
print_r( $bitly->getInfoArray($long));
12
13
*/
14
15
if (class_exists('Bitly')) {
16
    return true;
17
}
18
19
class Bitly
20
{
21
22
    protected $api          = 'http://api.bit.ly/';
23
    private   $format       = 'json';
24
    private   $version      = '2.0.1';
25
    private   $validActions = array(
26
        'shorten',
27
        'stats',
28
        'info',
29
        'expand'
30
    );
31
32
    public function __construct($login, $apiKey)
33
    {
34
        $this->login        = $login;
0 ignored issues
show
Bug introduced by
The property login 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...
35
        $this->apiKey       = $apiKey;
0 ignored issues
show
Bug introduced by
The property apiKey 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...
36
        $this->statusCode   = 'OK';
0 ignored issues
show
Bug introduced by
The property statusCode 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...
37
        $this->errorMessage = '';
0 ignored issues
show
Bug introduced by
The property errorMessage 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...
38
        $this->errorCode    = '';
0 ignored issues
show
Bug introduced by
The property errorCode 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...
39
        return true;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
40
    }
41
42
    private function setError($message, $code = 101)
43
    {
44
        $this->errorCode    = $code;
45
        $this->errorMessage = $message;
46
        $this->statusCode   = 'ERROR';
47
    }
48
49
    public function validAction($action)
50
    {
51
        if (in_array($action, $this->validActions)) {
52
            return true;
53
        }
54
        $this->setError("Undefined method $action", 202);
55
        return false;
56
    }
57
58
    public function error()
59
    {
60
        $ret = array(
61
            'errorCode'    => $this->errorCode,
62
            'errorMessage' => $this->errorMessage,
63
            'statusCode'   => $this->statusCode
64
        );
65
66
        // Function used for passing empty result sometimes.
67
        if ($this->statusCode === 'OK') {
68
            $ret['results'] = array();
69
        }
70
        if ($this->format === 'json') {
71
            return json_encode($ret);
72
        } else {
73
            throw new Exception('Unsupported format');
74
        }
75
    }
76
77
    public function shorten($message)
78
    {
79
80
        $postFields = '';
81
        preg_match_all("/http(s?):\/\/[^( |$|\]|,|\\\)]+/i", $message, $matches);
82
83
        for ($i = 0; $i < count($matches[0]); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
84
            $curr = $matches[0][$i];
85
            // ignore bitly urls
86
            if (!strstr($curr, 'http://bit.ly')) {
87
                $postFields .= '&longUrl=' . urlencode($curr);
88
            }
89
        }
90
91
        // nothing to shorten, return empty result
92
        if (!strlen($postFields)) {
93
            return $this->error();
94
        }
95
        return $this->process('shorten', $postFields);
96
    }
97
98
    public function expand($message)
99
    {
100
        $postFields = '&hash=' . $this->getHash($message);
101
        return $this->process('expand', $postFields);
102
    }
103
104
    public function info($bitlyUrl)
105
    {
106
        $hash       = $this->getHash($bitlyUrl);
107
        $postFields = '&hash=' . $hash;
108
        return $this->process('info', $postFields);
109
    }
110
111
    public function stats($bitlyUrl)
112
    {
113
        // Take only first hash or url. Ignore others.
114
        $a          = split(',', $bitlyUrl);
115
        $postFields = '&hash=' . $this->getHash($a[0]);
116
        return $this->process('stats', $postFields);
117
    }
118
119
    protected function process($action, $postFields)
120
    {
121
        $ch = curl_init($this->api . $action);
122
123
        $postFields = 'version=' . $this->version . $postFields;
124
        $postFields .= '&format=' . $this->format;
125
        $postFields .= '&history=1';
126
127
        curl_setopt($ch, CURLOPT_USERPWD, $this->login . ':' . $this->apiKey);
128
        curl_setopt($ch, CURLOPT_POST, 1);
129
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
130
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
131
132
        $response = curl_exec($ch);
133
134
        curl_close($ch);
135
136
        return $response;
137
    }
138
139
    public function setReturnFormat($format)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
140
    {
141
        // needed for restoration
142
        $this->oldFormat = $this->format;
0 ignored issues
show
Bug introduced by
The property oldFormat does not seem to exist. Did you mean format?

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...
143
        $this->format    = $format;
144
        return $this->format;
145
    }
146
147
    private function restoreFormat()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
148
    {
149
        if (!empty($this->oldFormat)) {
0 ignored issues
show
Bug introduced by
The property oldFormat does not seem to exist. Did you mean format?

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...
150
            $this->format = $this->oldFormat;
0 ignored issues
show
Bug introduced by
The property oldFormat does not seem to exist. Did you mean format?

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...
151
        }
152
        return $this->format;
153
    }
154
155
    // expect url, shortened url or hash
156
    public function getHash($message)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
157
    {
158
        // if url and not bit.ly get shortened first
159
        if (strstr($message, 'http://') && !strstr($message, 'http://bit.ly')) {
160
            $message = $this->shortenSingle($message);
161
        }
162
        $hash = str_replace('http://bit.ly/', '', $message);
163
        return $hash;
164
    }
165
166
    public function shortenSingle($message)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
167
    {
168
        $this->setReturnFormat('json');
169
        $data = json_decode($this->shorten($message), true);
170
        // return to previous state.
171
        $this->restoreFormat();
172
173
        // replace every long url with short one
174
        foreach ($data['results'] as $url => $d) {
175
            $message = str_replace($url, $d['shortUrl'], $message);
176
        }
177
        return $message;
178
    }
179
180
    public function expandSingle($shortUrl)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
181
    {
182
        $this->setReturnFormat('json');
183
        $data = json_decode($this->expand($shortUrl), true);
184
        $this->restoreFormat();
185
        return $data['results'][$this->getHash($shortUrl)]['longUrl'];
186
    }
187
188 View Code Duplication
    public function getInfoArray($url)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
189
    {
190
        $this->setReturnFormat('json');
191
        $json = $this->info($url);
192
        $this->restoreFormat();
193
        $data = json_decode($json, true);
194
195
        $this->infoArray = array_pop($data['results']);
0 ignored issues
show
Bug introduced by
The property infoArray 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...
196
        return $this->infoArray;
197
    }
198
199 View Code Duplication
    public function getStatsArray($url)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
200
    {
201
        $this->setReturnFormat('json');
202
        $json = $this->stats($url);
203
        $this->restoreFormat();
204
        $data             = json_decode($json, true);
205
        $this->statsArray = $data['results'];
0 ignored issues
show
Bug introduced by
The property statsArray 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...
206
        return $this->statsArray;
207
    }
208
209
    public function getClicks()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
210
    {
211
        return $this->statsArray['clicks'];
212
    }
213
214
    // get thumbnail (small, middle, large)
215
    public function getThumbnail($size = 'small')
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
216
    {
217
        if (!in_array($size, array('small', 'medium', 'large'))) {
218
            throw new Exception('Invalid size value');
219
        }
220
        if (empty($this->infoArray)) {
221
            throw new Exception('Info not loaded');
222
        }
223
        return $this->infoArray['thumbnail'][$size];
224
    }
225
226
    public function getTitle()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
227
    {
228
        return $this->infoArray['htmlTitle'];
229
    }
230
}
231