Completed
Push — master ( 2c0cde...363a2f )
by Tyler
03:02 queued 44s
created

PeopleMatter::handleResponse()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.5125
c 0
b 0
f 0
cc 6
eloc 16
nc 5
nop 1
1
<?php
2
3
namespace Zenapply\PeopleMatter\Api;
4
5
use GuzzleHttp\Client;
6
7
class PeopleMatter
8
{
9
    const V3 = 'v3';
10
11
    protected $host;
12
    protected $version;
13
    protected $client;
14
    protected $token;
15
16
    /**
17
     * Creates a PeopleMatter instance that can register and unregister webhooks with the API
18
     * @param string $token   The API token to authenticate with
19
     * @param string $version The API version to use
20
     * @param string $host    The Host URL
21
     * @param string $client  The Client instance that will handle the http request
22
     */
23
    public function __construct($token, $version = self::V3, $host = "api-ssl.bitly.com", Client $client = null){
24
        $this->client = $client;
25
        $this->token = $token;
26
        $this->version = $version;
27
        $this->host = $host;
28
    }
29
30
    public function shorten($url, $encode = true)
31
    {
32
        if (empty($url)) {
33
            throw new BitlyErrorException("The URL is empty!");
34
        }
35
36
        $url = $this->fixUrl($url, $encode);
37
38
        $data = $this->exec($this->buildRequestUrl($url));
39
            
40
        return $data['data']['url'];
41
    }
42
43
    /**
44
     * Returns the response data or throws an Exception if it was unsuccessful
45
     * @param  string $raw The data from the response
46
     * @return array
47
     */
48
    protected function handleResponse($raw){
49
        $data = json_decode($raw,true);
50
51
        if(!isset($data['status_code'])){
52
            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 Zenapply\PeopleMatter\Ap...eMatter::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...
53
        }
54
55
        if($data['status_code']>=300 || $data['status_code']<200){
56
            switch ($data['status_txt']) {
57
                case 'RATE_LIMIT_EXCEEDED':
58
                    throw new BitlyRateLimitException;
59
                    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...
60
61
                case 'INVALID_LOGIN':
62
                    throw new BitlyAuthException;
63
                    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...
64
65
                default:
66
                    throw new BitlyErrorException($data['status_txt']);
67
                    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...
68
            }
69
        }
70
        return $data;
71
    }
72
73
    /**
74
     * Returns a corrected URL
75
     * @param  string  $url    The URL to modify
76
     * @param  boolean $encode Whether or not to encode the URL
77
     * @return string          The corrected URL
78
     */
79
    protected function fixUrl($url, $encode){
80
        if(strpos($url, "http") !== 0){
81
            $url = "http://".$url;
82
        }
83
84
        if($encode){
85
            $url = urlencode($url);
86
        }
87
88
        return $url;
89
    }
90
91
    /**
92
     * Builds the request URL to the PeopleMatter API for a specified action
93
     * @param  string $action The long URL
94
     * @param  string $action The API action
95
     * @return string         The URL
96
     */
97
    protected function buildRequestUrl($url,$action = "shorten"){
98
        return "https://{$this->host}/{$this->version}/{$action}?access_token={$this->token}&format=json&longUrl={$url}";
99
    }
100
101
    /**
102
     * Returns the Client instance
103
     * @return Client
104
     */
105
    protected function getRequest(){
106
        $client = $this->client;
107
        if(!$client instanceof Client){
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Client does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
108
            $client = new Client();
109
        }
110
        return $client;
111
    }
112
113
    /**
114
     * Executes a CURL request to the PeopleMatter API
115
     * @param  string $url    The URL to send to
116
     * @return mixed          The response data
117
     */ 
118
    protected function exec($url)
119
    {
120
        $client = $this->getRequest();
121
        $response = $client->request('GET',$url);
122
        return $this->handleResponse($response->getBody());
123
    }
124
}
125