Issues (1)

Security Analysis    no request data  

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

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 Gerfaut\Yelp;
4
5
use Gerfaut\Yelp\Exception\ApiException;
6
use Gerfaut\Yelp\Exception\DeserializeException;
7
use Gerfaut\Yelp\Model\AutocompleteResponse;
8
use Gerfaut\Yelp\Model\Business;
9
use Gerfaut\Yelp\Model\BusinessesResponse;
10
use Gerfaut\Yelp\Model\ReviewsResponse;
11
use GuzzleHttp\Exception\ClientException;
12
use JMS\Serializer\Serializer;
13
use JMS\Serializer\SerializerBuilder;
14
use GuzzleHttp\Client as HttpClient;
15
use Doctrine\Common\Annotations\AnnotationRegistry;
16
17
/**
18
 * Class Client
19
 * @package Gerfaut\Yelp
20
 */
21
class Client
22
{
23
    /**
24
     * Search path
25
     *
26
     * @var string
27
     */
28
    protected $searchPath = '/v3/businesses/search';
29
30
    /**
31
     * Business path
32
     *
33
     * @var string
34
     */
35
    protected $businessPath = '/v3/businesses/%s';
36
37
    /**
38
     * Phone search path
39
     *
40
     * @var string
41
     */
42
    protected $phoneSearchPath = '/v3/businesses/search/phone';
43
44
    /**
45
     * Reviews path
46
     *
47
     * @var string
48
     */
49
    protected $reviewsPath = '/v3/businesses/%s/reviews';
50
51
    /**
52
     * Transactions path
53
     *
54
     * @var string
55
     */
56
    protected $transactionsPath = '/v3/transactions/%s/search';
57
58
    /**
59
     * Autocomplete path
60
     *
61
     * @var string
62
     */
63
    protected $autocompletePath = '/v3/autocomplete';
64
65
    /**
66
     * Oauth2 token path
67
     *
68
     * @var string
69
     */
70
    protected $oauth2TokenPath = '/oauth2/token';
71
72
    /**
73
     * Default search term
74
     *
75
     * @var string
76
     */
77
    protected $defaultTerm = 'restaurants';
78
79
    /**
80
     * Default location
81
     *
82
     * @var string
83
     */
84
    protected $defaultLocation = 'USA';
85
86
    /**
87
     * Default search limit
88
     *
89
     * @var integer
90
     */
91
    protected $searchLimit = 10;
92
93
    /**
94
     * API host url
95
     *
96
     * @var string
97
     */
98
    protected $apiHost;
99
100
    /**
101
     * Consumer key
102
     *
103
     * @var string
104
     */
105
    protected $consumerKey;
106
107
    /**
108
     * Consumer secret
109
     *
110
     * @var string
111
     */
112
    protected $consumerSecret;
113
114
    /**
115
     * Access token
116
     *
117
     * @var string
118
     */
119
    protected $accessToken;
120
121
    /**
122
     * HttpClient used to query the API
123
     *
124
     * @var HttpClient
125
     */
126
    protected $httpClient;
127
128
    /**
129
     * @var Serializer
130
     */
131
    protected $serializer;
132
133
    /**
134
     * Client constructor.
135
     * @param array $configuration
136
     */
137 26
    public function __construct($configuration = [])
138
    {
139 26
        $this->parseConfiguration($configuration)
140 26
            ->createHttpClient();
141
142 26
        $this->serializer = SerializerBuilder::create()->build();
143 26
    }
144
145
146
    /**
147
     * Get autocomplete suggestions
148
     *
149
     * @param array $attributes
150
     *
151
     * @return AutocompleteResponse The response object from the request
152
     */
153 2
    public function getAutocompleteSuggestions($attributes = [])
154
    {
155 2
        $path = $this->autocompletePath."?".$this->prepareQueryParams($attributes);
156
157 2
        return $this->request($path, Model\AutocompleteResponse::class);
158
    }
159
160
    /**
161
     * Query the Business API by business id
162
     *
163
     * @param    string $businessId The ID of the business to query
164
     *
165
     * @return   Business The response object from the request
166
     */
167 10
    public function getBusiness($businessId)
168
    {
169 10
        $businessPath = sprintf($this->businessPath, urlencode($businessId));
170
171 10
        return $this->request($businessPath, Model\Business::class);
172
    }
173
174
    /**
175
     * Get reviews for business by ID string
176
     *
177
     * @param string $businessId
178
     *
179
     * @return ReviewsResponse The response object from the request
180
     */
181 2
    public function getReviews($businessId)
182
    {
183 2
        $path = sprintf($this->reviewsPath, urlencode($businessId));
184
185 2
        return $this->request($path, Model\ReviewsResponse::class);
186
    }
187
188
    /**
189
     * Get transactions - food delivery in the US
190
     *
191
     * @param array $attributes
192
     *
193
     * @return BusinessesResponse  The response object from the request
194
     */
195 4
    public function getTransactions($attributes = [])
196
    {
197
        // default transaction type
198 4
        $transactionType = 'delivery';
199
200 4
        if (isset($attributes['transaction_type'])) {
201 2
            $transactionType = $attributes['transaction_type'];
202 2
            unset($attributes['transaction_type']);
203 2
        }
204
205 4
        $path = $this->prepareQueryParams($attributes);
206
207 4
        $path = sprintf($this->transactionsPath, urlencode($transactionType))."?".$path;
208
209 4
        return $this->request($path, Model\BusinessesResponse::class);
210
    }
211
212
    /**
213
     * Query the Search API by a search term and location
214
     *
215
     * @param    array $attributes Query attributes
216
     *
217
     * @return   BusinessesResponse The response object from the request
218
     */
219 4
    public function search($attributes = [])
220
    {
221 4
        $queryString = $this->buildQueryParamsForSearch($attributes);
222 4
        $searchPath = $this->searchPath."?".$queryString;
223
224 4
        return $this->request($searchPath, Model\BusinessesResponse::class);
225
    }
226
227
    /**
228
     * Search for businesses by phone number
229
     *
230
     * @param string $phone
231
     *
232
     * @return BusinessesResponse The response object from the request
233
     */
234 2
    public function searchByPhone($phone)
235
    {
236 2
        $path = $this->phoneSearchPath."?".$this->prepareQueryParams(['phone' => $phone]);
237
238 2
        return $this->request($path, Model\BusinessesResponse::class);
239
    }
240
241
    /**
242
     * Set default location
243
     *
244
     * @param string $location
245
     *
246
     * @return Client
247
     */
248 2
    public function setDefaultLocation($location)
249
    {
250 2
        $this->defaultLocation = $location;
251
252 2
        return $this;
253
    }
254
    /**
255
     * Set default term
256
     *
257
     * @param string $term
258
     *
259
     * @return Client
260
     */
261 2
    public function setDefaultTerm($term)
262
    {
263 2
        $this->defaultTerm = $term;
264
265 2
        return $this;
266
    }
267
268
    /**
269
     * Set search limit
270
     *
271
     * @param integer $limit
272
     *
273
     * @return Client
274
     */
275 2
    public function setSearchLimit($limit)
276
    {
277 2
        if (is_int($limit)) {
278 2
            $this->searchLimit = $limit;
279 2
        }
280
281 2
        return $this;
282
    }
283
284
    /**
285
     * Updates the yelp client's http client to the given http client. Client.
286
     *
287
     * @param HttpClient $client
288
     *
289
     * @return  Client
290
     */
291 26
    public function setHttpClient(HttpClient $client)
292
    {
293 26
        $this->httpClient = $client;
294
295 26
        return $this;
296
    }
297
298
    /**
299
     * Get new access token from Yelp API.
300
     * @return Client
301
     * @throws ApiException
302
     */
303 24
    protected function setAccessToken()
304
    {
305
        try {
306
            // try to get access token from API
307 24
            $auth2Response = $this->httpClient->request(
308 24
                'POST',
309 24
                'https://'.$this->apiHost.$this->oauth2TokenPath,
310
                [
311
                    'query' => [
312 24
                        'grant_type' => 'client_credentials',
313 24
                        'client_id' => $this->consumerKey,
314 24
                        'client_secret' => $this->consumerSecret,
315
                    ]
316 24
                ]
317 24
            );
318 24
        } catch (ClientException $e) {
319 4
            $exception = new ApiException($e->getMessage());
320 4
            throw $exception->setResponseBody($e->getResponse()->getBody());
321
        }
322
323 20
        $decodedArr = json_decode($auth2Response->getBody(), true);
324
325 20
        if (isset($decodedArr['access_token'])) {
326 20
            $this->accessToken = $decodedArr['access_token'];
327 20
        }
328
329 20
        return $this;
330
    }
331
332
    /**
333
     * Build query string params using defaults for search() functionality
334
     *
335
     * @param  array $attributes
336
     *
337
     * @return string
338
     */
339 10
    protected function buildQueryParamsForSearch($attributes = [])
340
    {
341
        $defaults = array(
342 10
            'term' => $this->defaultTerm,
343 10
            'location' => $this->defaultLocation,
344 10
            'limit' => $this->searchLimit
345 10
        );
346
347 10
        $attributes = array_merge($defaults, $attributes);
348
349 10
        return $this->prepareQueryParams($attributes);
350
    }
351
352
    /**
353
     * Build unsigned url
354
     *
355
     * @param  string $host
356
     * @param  string $path
357
     *
358
     * @return string   Unsigned url
359
     */
360 20
    protected function buildUnsignedUrl($host, $path)
361
    {
362 20
        return "https://".$host.$path;
363
    }
364
365
    /**
366
     * Builds and sets a preferred http client.
367
     *
368
     * @return Client
369
     */
370 26
    protected function createHttpClient()
371
    {
372 26
        $client = new HttpClient();
373
374 26
        return $this->setHttpClient($client);
375
    }
376
377
    /**
378
     * Maps legacy configuration keys to updated keys.
379
     *
380
     * @param  array $configuration
381
     *
382
     * @return array
383
     */
384 26
    protected function mapConfiguration(array $configuration)
385
    {
386
        array_walk($configuration, function ($value, $key) use (&$configuration) {
387 26
            $newKey = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key))));
388 26
            $configuration[$newKey] = $value;
389 26
        });
390
391 26
        return $configuration;
392
    }
393
394
    /**
395
     * Parse configuration using defaults
396
     *
397
     * @param  array $configuration
398
     *
399
     * @return client
400
     */
401 26
    protected function parseConfiguration($configuration = [])
402
    {
403
        $defaults = array(
404 26
            'consumerKey' => null,
405 26
            'consumerSecret' => null,
406
            'apiHost' => 'api.yelp.com'
407 26
        );
408 26
        $configuration = array_merge($defaults, $this->mapConfiguration($configuration));
409 26
        array_walk($configuration, [$this, 'setConfig']);
410
411 26
        return $this;
412
    }
413
414
    /**
415
     * Attempts to set a given value.
416
     *
417
     * @param mixed   $value
418
     * @param string  $key
419
     *
420
     * @return Client
421
     */
422 26
    protected function setConfig($value, $key)
423
    {
424 26
        if (property_exists($this, $key)) {
425 26
            $this->$key = $value;
426 26
        }
427
428 26
        return $this;
429
    }
430
431
    /**
432
     * Updates query params array to apply yelp specific formatting rules.
433
     *
434
     * @param  array $params
435
     *
436
     * @return string
437
     */
438
    protected function prepareQueryParams($params = [])
439
    {
440 12
        array_walk($params, function ($value, $key) use (&$params) {
441 12
            if (is_bool($value)) {
442
                $params[$key] = $value ? 'true' : 'false';
443
            }
444 12
        });
445
446 12
        return http_build_query($params);
447
    }
448
449
    /**
450
     * Makes a request to the Yelp API and returns the response
451
     *
452
     * @param    string $path The path of the APi after the domain
453
     * @param    string $fullClassName The full qualified name of the class to be used to deserialize the response
454
     * @return stdClass The JSON response from the request
455
     * @throws DeserializeException
456
     * @throws  ApiException
457
     */
458 24
    protected function request($path, $fullClassName)
459 2
    {
460
        //Autoload JMS annotations
461 24
        AnnotationRegistry::registerLoader('class_exists');
462
463 24
        if (empty($this->accessToken)) {
464 24
            $this->setAccessToken();
465 20
        }
466
467 20
        $url = $this->buildUnsignedUrl($this->apiHost, $path);
468
469
        //try {
470 20
            $response = $this->httpClient->request(
471 20
                'get',
472 20
                $url,
473
                ['headers' =>
474 20
                    ['Authorization' => "Bearer {$this->accessToken}"]
475 20
                ]
476 20
            );
477
        //} catch (\Exception $e) {
478
        //    $exception = new ApiException($e->getMessage());
479
        //    throw $exception->setResponseBody($e->getResponse()->getBody());
480
        //}
481
482
        try {
483 20
            return $this->serializer->deserialize($response->getBody(), $fullClassName, 'json');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->serializer...fullClassName, 'json'); (object|array|integer|double|string|boolean) is incompatible with the return type documented by Gerfaut\Yelp\Client::request of type Gerfaut\Yelp\stdClass.

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...
484 2
        } catch (\Exception $e) {
485 2
            throw new DeserializeException("Error in deserialization (".$response->getBody().
486 2
                                                    " ----> ".$fullClassName.")", -1, $e);
487
        }
488
    }
489
}
490