Bitly::shorten()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 2
crap 2
1
<?php
2
3
namespace LeadThread\Bitly;
4
5
use LeadThread\Bitly\Exceptions\BitlyAuthException;
6
use LeadThread\Bitly\Exceptions\BitlyErrorException;
7
use LeadThread\Bitly\Exceptions\BitlyRateLimitException;
8
use GuzzleHttp\Client;
9
10
class Bitly
11
{
12
    const V3 = 'v3';
13
14
    protected $host;
15
    protected $version;
16
    protected $client;
17
    protected $token;
18
19
    /**
20
     * Creates a Bitly instance that can register and unregister webhooks with the API
21
     * @param string $token   The API token to authenticate with
22
     * @param string $version The API version to use
23
     * @param string $host    The Host URL
24
     * @param string $client  The Client instance that will handle the http request
25
     */
26 27
    public function __construct($token, $version = self::V3, $host = "api-ssl.bitly.com", Client $client = null){
27 27
        $this->client = $client;
28 27
        $this->token = $token;
29 27
        $this->version = $version;
30 27
        $this->host = $host;
31 27
    }
32
33 12
    public function shorten($url, $encode = true)
34
    {
35 12
        if (empty($url)) {
36 3
            throw new BitlyErrorException("The URL is empty!");
37
        }
38
39 9
        $url = $this->fixUrl($url, $encode);
40
41 9
        $data = $this->exec($this->buildRequestUrl($url));
42
            
43 6
        return $data['data']['url'];
44
    }
45
46
    /**
47
     * Returns the response data or throws an Exception if it was unsuccessful
48
     * @param  string $raw The data from the response
49
     * @return array
50
     */
51 9
    protected function handleResponse($raw){
52 9
        $data = json_decode($raw,true);
53
54 9
        if(!isset($data['status_code'])){
55
            return $raw;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $raw; (string) is incompatible with the return type documented by LeadThread\Bitly\Bitly::handleResponse of type array.

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...
56
        }
57
58 9
        if($data['status_code']>=300 || $data['status_code']<200){
59 3
            switch ($data['status_txt']) {
60 3
                case 'RATE_LIMIT_EXCEEDED':
61
                    throw new BitlyRateLimitException;
62
                    break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
63
64 3
                case 'INVALID_LOGIN':
65
                    throw new BitlyAuthException;
66
                    break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
67
68 3
                default:
69 3
                    throw new BitlyErrorException($data['status_txt']);
70
                    break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
71 3
            }
72
        }
73 6
        return $data;
74
    }
75
76
    /**
77
     * Returns a corrected URL
78
     * @param  string  $url    The URL to modify
79
     * @param  boolean $encode Whether or not to encode the URL
80
     * @return string          The corrected URL
81
     */
82 18
    protected function fixUrl($url, $encode){
83 18
        if(strpos($url, "http") !== 0){
84 12
            $url = "http://".$url;
85 12
        }
86
87 18
        if($encode){
88 12
            $url = urlencode($url);
89 12
        }
90
91 18
        return $url;
92
    }
93
94
    /**
95
     * Builds the request URL to the Bitly API for a specified action
96
     * @param  string $action The long URL
97
     * @param  string $action The API action
98
     * @return string         The URL
99
     */
100 12
    protected function buildRequestUrl($url,$action = "shorten"){
101 12
        return "https://{$this->host}/{$this->version}/{$action}?access_token={$this->token}&format=json&longUrl={$url}";
102
    }
103
104
    /**
105
     * Returns the Client instance
106
     * @return Client
107
     */
108 9
    protected function getRequest(){
109 9
        $client = $this->client;
110 9
        if(!$client instanceof Client){
111
            $client = new Client();
112
        }
113 9
        return $client;
114
    }
115
116
    /**
117
     * Executes a CURL request to the Bitly API
118
     * @param  string $url    The URL to send to
119
     * @return mixed          The response data
120
     */ 
121 9
    protected function exec($url)
122
    {
123 9
        $client = $this->getRequest();
124 9
        $response = $client->request('GET',$url);
125 9
        return $this->handleResponse($response->getBody());
126
    }
127
}
128