Failed Conditions
Pull Request — master (#25)
by Chad
02:06
created

src/Client.php (1 issue)

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
7
/**
8
 * PHP Client for the Marvel API.
9
 */
10
class Client implements ClientInterface
11
{
12
    /**
13
     * The public api key issued by Marvel.
14
     *
15
     * @var string
16
     */
17
    private $publicApiKey;
18
19
    /**
20
     * The private api key issued by Marvel.
21
     *
22
     * @var string
23
     */
24
    private $privateApiKey;
25
26
    /**
27
     * Adapter implementation.
28
     *
29
     * @var Adapter\AdapterInterface
30
     */
31
    private $adapter;
32
33
    /**
34
     * Cache implementation.
35
     *
36
     * @var Cache\CacheInterface
37
     */
38
    private $cache;
39
40
    /**
41
     * The Marvel API url.
42
     *
43
     * @const string
44
     */
45
    const BASE_URL = 'http://gateway.marvel.com/v1/public/';
46
47
    /**
48
     * Construct a new Client.
49
     *
50
     * @param string                   $privateApiKey The private api key issued by Marvel.
51
     * @param string                   $publicApiKey  The public api key issued by Marvel.
52
     * @param Adapter\AdapterInterface $adapter       Implementation of a client adapter.
53
     * @param Cache\CacheInterface     $cache         Implementation of Cache.
54
     */
55
    final public function __construct(
56
        $privateApiKey,
57
        $publicApiKey,
58
        Adapter\AdapterInterface $adapter = null,
59
        Cache\CacheInterface $cache = null
60
    ) {
61
        Util::throwIfNotType(['string' => [$privateApiKey, $publicApiKey]], true);
62
63
        $this->privateApiKey = $privateApiKey;
64
        $this->publicApiKey = $publicApiKey;
65
        $this->adapter = $adapter ?: new Adapter\CurlAdapter();
66
        $this->cache = $cache;
67
    }
68
69
    /**
70
     * Execute a search request against the Marvel API.
71
     *
72
     * @param string $resource The API resource to search for.
73
     * @param array  $filters  Array of search criteria to use in request.
74
     *
75
     * @return ResponseInterface
76
     *
77
     * @throws \InvalidArgumentException Thrown if $resource is empty or not a string.
78
     */
79
    final public function search($resource, array $filters = [])
80
    {
81
        if (!is_string($resource) || trim($resource) == '') {
82
            throw new \InvalidArgumentException('$resource must be a non-empty string');
83
        }
84
85
        $filters['apikey'] = $this->publicApiKey;
86
        $timestamp = time();
87
        $filters['ts'] = $timestamp;
88
        $filters['hash'] = md5($timestamp . $this->privateApiKey . $this->publicApiKey);
89
        $url = self::BASE_URL . urlencode($resource) . '?' . http_build_query($filters);
90
91
        return $this->send(new Request($url, 'GET', ['Accept' =>  'application/json']));
92
    }
93
94
    /**
95
     * Execute a GET request against the Marvel API for a single resource.
96
     *
97
     * @param string  $resource The API resource to search for.
98
     * @param integer $id       The id of the API resource.
99
     *
100
     * @return ResponseInterface
101
     */
102
    final public function get($resource, $id)
103
    {
104
        Util::throwIfNotType(['string' => [$resource], 'int' => [$id]], true);
105
106
        $timestamp = time();
107
        $query = [
108
            'apikey' => $this->publicApiKey,
109
            'ts' => $timestamp,
110
            'hash' => md5($timestamp . $this->privateApiKey . $this->publicApiKey),
111
        ];
112
113
        $url = self::BASE_URL . urlencode($resource) . "/{$id}?" . http_build_query($query);
114
115
        return $this->send(new Request($url, 'GET', ['Accept' =>  'application/json']));
116
    }
117
118
    /**
119
     * Send the given API Request.
120
     *
121
     * @param RequestInterface $request The request to send.
122
     *
123
     * @return ResponseInterface
124
     */
125
    final private function send(RequestInterface $request)
126
    {
127
        $response = $this->getFromCache($request);
128
        if ($response !== null) {
129
            return $response;
130
        }
131
132
        $response = $this->adapter->send($request);
133
134
        if ($this->cache !== null) {
135
            $this->cache->set($request, $response);
136
        }
137
138
        return $response;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $response; (Chadicus\Marvel\Api\Adapter\ResponseInterface) is incompatible with the return type documented by Chadicus\Marvel\Api\Client::send 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...
139
    }
140
141
    /**
142
     * Retrieve the Response for the given Request from cache.
143
     *
144
     * @param RequestInterface $request The request to send.
145
     *
146
     * @return ResponseInterface|null Returns the cached Response or null if it does not exist.
147
     */
148
    final private function getFromCache(RequestInterface $request)
149
    {
150
        if ($this->cache === null) {
151
            return null;
152
        }
153
154
        return $this->cache->get($request);
155
    }
156
157
    /**
158
     * Allow calls such as $client->characters();
159
     *
160
     * @param string $name      The name of the api resource.
161
     * @param array  $arguments The parameters to pass to get() or search().
162
     *
163
     * @return Collection|EntityInterface
164
     */
165
    final public function __call($name, array $arguments)
166
    {
167
        $resource = strtolower($name);
168
        $parameters = array_shift($arguments);
169
        if ($parameters === null || is_array($parameters)) {
170
            return new Collection($this, $resource, $parameters ?: []);
171
        }
172
173
        $response = $this->get($resource, $parameters);
174
        $results = $response->getDataWrapper()->getData()->getResults();
175
        if (empty($results)) {
176
            return null;
177
        }
178
179
        return $results[0];
180
    }
181
}
182