Failed Conditions
Pull Request — master (#26)
by Chad
03:08
created

src/Client.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Chadicus\Marvel\Api;
4
5
use DominionEnterprises\Util;
6
use Psr\Http\Message\RequestInterface;
7
use Psr\Http\Message\ResponseInterface;
8
use Zend\Diactoros\Request;
9
10
/**
11
 * PHP Client for the Marvel API.
12
 */
13
class Client implements ClientInterface
14
{
15
    /**
16
     * The public api key issued by Marvel.
17
     *
18
     * @var string
19
     */
20
    private $publicApiKey;
21
22
    /**
23
     * The private api key issued by Marvel.
24
     *
25
     * @var string
26
     */
27
    private $privateApiKey;
28
29
    /**
30
     * Adapter implementation.
31
     *
32
     * @var Adapter\AdapterInterface
33
     */
34
    private $adapter;
35
36
    /**
37
     * Cache implementation.
38
     *
39
     * @var Cache\CacheInterface
40
     */
41
    private $cache;
42
43
    /**
44
     * The Marvel API url.
45
     *
46
     * @const string
47
     */
48
    const BASE_URL = 'http://gateway.marvel.com/v1/public/';
49
50
    /**
51
     * Construct a new Client.
52
     *
53
     * @param string                   $privateApiKey The private api key issued by Marvel.
54
     * @param string                   $publicApiKey  The public api key issued by Marvel.
55
     * @param Adapter\AdapterInterface $adapter       Implementation of a client adapter.
56
     * @param Cache\CacheInterface     $cache         Implementation of Cache.
57
     */
58
    final public function __construct(
59
        $privateApiKey,
60
        $publicApiKey,
61
        Adapter\AdapterInterface $adapter = null,
62
        Cache\CacheInterface $cache = null
63
    ) {
64
        Util::throwIfNotType(['string' => [$privateApiKey, $publicApiKey]], true);
65
66
        $this->privateApiKey = $privateApiKey;
67
        $this->publicApiKey = $publicApiKey;
68
        $this->adapter = $adapter ?: new Adapter\CurlAdapter();
69
        $this->cache = $cache;
70
    }
71
72
    /**
73
     * Execute a search request against the Marvel API.
74
     *
75
     * @param string $resource The API resource to search for.
76
     * @param array  $filters  Array of search criteria to use in request.
77
     *
78
     * @return ResponseInterface
79
     *
80
     * @throws \InvalidArgumentException Thrown if $resource is empty or not a string.
81
     */
82
    final public function search($resource, array $filters = [])
83
    {
84
        if (!is_string($resource) || trim($resource) == '') {
85
            throw new \InvalidArgumentException('$resource must be a non-empty string');
86
        }
87
88
        $filters['apikey'] = $this->publicApiKey;
89
        $timestamp = time();
90
        $filters['ts'] = $timestamp;
91
        $filters['hash'] = md5($timestamp . $this->privateApiKey . $this->publicApiKey);
92
        $url = self::BASE_URL . urlencode($resource) . '?' . http_build_query($filters);
93
94
        return $this->send(new Request($url, 'GET', 'php://temp', ['Accept' =>  'application/json']));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->send(new \... 'application/json'))); (Psr\Http\Message\ResponseInterface) is incompatible with the return type declared by the interface Chadicus\Marvel\Api\ClientInterface::search of type Chadicus\Marvel\Api\ResponseInterface.

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...
95
    }
96
97
    /**
98
     * Execute a GET request against the Marvel API for a single resource.
99
     *
100
     * @param string  $resource The API resource to search for.
101
     * @param integer $id       The id of the API resource.
102
     *
103
     * @return ResponseInterface
104
     */
105
    final public function get($resource, $id)
106
    {
107
        Util::throwIfNotType(['string' => [$resource], 'int' => [$id]], true);
108
109
        $timestamp = time();
110
        $query = [
111
            'apikey' => $this->publicApiKey,
112
            'ts' => $timestamp,
113
            'hash' => md5($timestamp . $this->privateApiKey . $this->publicApiKey),
114
        ];
115
116
        $url = self::BASE_URL . urlencode($resource) . "/{$id}?" . http_build_query($query);
117
118
        return $this->send(new Request($url, 'GET', 'php://temp', ['Accept' =>  'application/json']));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->send(new \... 'application/json'))); (Psr\Http\Message\ResponseInterface) is incompatible with the return type declared by the interface Chadicus\Marvel\Api\ClientInterface::get of type Chadicus\Marvel\Api\ResponseInterface.

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...
119
    }
120
121
    /**
122
     * Send the given API Request.
123
     *
124
     * @param RequestInterface $request The request to send.
125
     *
126
     * @return ResponseInterface
127
     */
128
    final private function send(RequestInterface $request)
129
    {
130
        $response = $this->getFromCache($request);
131
        if ($response !== null) {
132
            return $response;
133
        }
134
135
        $response = $this->adapter->send($request);
136
137
        if ($this->cache !== null) {
138
            $this->cache->set($request, $response);
139
        }
140
141
        return $response;
142
    }
143
144
    /**
145
     * Retrieve the Response for the given Request from cache.
146
     *
147
     * @param RequestInterface $request The request to send.
148
     *
149
     * @return ResponseInterface|null Returns the cached Response or null if it does not exist.
150
     */
151
    final private function getFromCache(RequestInterface $request)
152
    {
153
        if ($this->cache === null) {
154
            return null;
155
        }
156
157
        return $this->cache->get($request);
158
    }
159
160
    /**
161
     * Allow calls such as $client->characters();
162
     *
163
     * @param string $name      The name of the api resource.
164
     * @param array  $arguments The parameters to pass to get() or search().
165
     *
166
     * @return Collection|EntityInterface
167
     */
168
    final public function __call($name, array $arguments)
169
    {
170
        $resource = strtolower($name);
171
        $parameters = array_shift($arguments);
172
        if ($parameters === null || is_array($parameters)) {
173
            return new Collection($this, $resource, $parameters ?: []);
174
        }
175
176
        $response = $this->get($resource, $parameters);
177
        if ($response->getStatusCode() !== 200) {
178
            return null;
179
        }
180
181
        $json = (string)$response->getBody();
182
        $dataWrapper = new DataWrapper(json_decode($json, true));
183
        $results = $dataWrapper->getData()->getResults();
184
        if (empty($results)) {
185
            return null;
186
        }
187
188
        return $results[0];
189
    }
190
}
191