Passed
Push — master ( 1f5e72...7f5bc2 )
by Justin
02:15
created

PageApi::call()   B

Complexity

Conditions 6
Paths 14

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 15
cts 15
cp 1
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 14
nc 14
nop 2
crap 6
1
<?php
2
3
namespace Vssl\Render;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Exception\ClientException;
7
use GuzzleHttp\Exception\ConnectException;
8
use Journey\Cache\CacheAdapterInterface;
9
use Psr\Http\Message\RequestInterface;
10
11
class PageApi
12
{
13
    /**
14
     * Guzzle HTTP interface.
15
     *
16
     * @var \GuzzleHTTP\Client
17
     */
18
    protected $http;
19
20
    /**
21
     * A cache adapter for storing results.
22
     *
23
     * @var \Journey\Cache\CacheAdapterInterface
24
     */
25
    protected $cache;
26
27
    /**
28
     * Number of seconds responses should be cached for.
29
     *
30
     * @var integer
31
     */
32
    protected $ttl;
33
34
    /**
35
     * Initialize the page api methods.
36
     */
37 7
    public function __construct(RequestInterface $request, array $config)
38
    {
39 7
        $this->ttl = $config['cache_ttl'];
40 7
        $this->cache = $config['cache'];
41 7
        $this->http = new Client([
42 7
            'base_uri' => $config['base_uri'],
43
            'headers' => [
44 7
                'X-Render-Host' => $request->getUri()->getHost(),
45
            ]
46 7
        ]);
47 7
    }
48
49
    /**
50
     * Get a particular page from the api.
51
     *
52
     * @param  string $path path of the page
53
     * @return array|false
54
     */
55 4
    public function getPage($path)
56
    {
57 4
        return $this->call("get", "/api/pages?slug=" . $path);
58
    }
59
60
    /**
61
     * Get a particular page from the api.
62
     *
63
     * @param  array $ids unique ids of pages to fetch data for.
64
     * @return array|false
65
     */
66
    public function getPagesById($ids)
67
    {
68 2
        $ids = array_filter(array_map(function ($id) {
69 2
            return is_numeric($id) ? (integer) $id : null;
70 2
        }, $ids));
71 2
        return $this->call("get", "/api/pages?ids=" . implode(",", $ids));
72
    }
73
74
    /**
75
     * Get a list of pages of a particular type from the api.
76
     *
77
     * @param  string $type type of pages to get.
78
     * @return array
79
     */
80
    public function getPagesByType($type)
81
    {
82
        return $this->call("get", "/api/pages?type=" . urlencode($type));
83
    }
84
85
    /**
86
     * Clear the cache of a given endpoint immediately.
87
     *
88
     * @param  string $method get/post/put
89
     * @param  string $url    endpoint to hit
90
     * @return $this
91
     */
92
    public function clearEndpoint($method, $url)
93
    {
94
        $cacheKey = md5(strtoupper($method) . "::" . $url);
95
        $this->cache->delete($cacheKey);
96
        return $this;
97
    }
98
99
    /**
100
     * Call a particular api endpoint.
101
     *
102
     * @return \Psr\Http\Message\ResponseInterface
103
     */
104 7
    public function call($method, $url)
105
    {
106 7
        $cacheKey = md5(strtoupper($method) . "::" . $url);
107
        try {
108 7
            if (!$value = $this->cache->get($cacheKey)) {
109 7
                $response = $this->http->request(strtoupper($method), $url);
110 5
            }
111 7
        } catch (ClientException $e) {
112 1
            $response = $e->getResponse();
113 2
        } catch (ConnectException $e) {
114 1
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Vssl\Render\PageApi::call of type Psr\Http\Message\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...
115
        }
116 6
        if (!isset($response)) {
117 1
            $response = \GuzzleHttp\Psr7\parse_response($value);
0 ignored issues
show
Bug introduced by
The variable $value does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
118 6
        } elseif ($this->ttl) {
119 3
            $this->cache->set($cacheKey, \GuzzleHttp\Psr7\str($response), time() + $this->ttl);
120 3
        }
121 6
        return $response;
122
    }
123
}
124