Completed
Push — master ( 565bd0...e6372b )
by Gareth
15:14
created

RemoteFetcher::findPageInList()   C

Complexity

Conditions 7
Paths 9

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 34
rs 6.7272
cc 7
eloc 18
nc 9
nop 2
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 19 and the first side effect is on line 2.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
declare(strict_types=1);
3
4
namespace GarethEllis\Tldr\Fetcher;
5
6
use GarethEllis\Tldr\Fetcher\Exception\PageNotFoundException;
7
use GarethEllis\Tldr\Page\TldrPage;
8
use GuzzleHttp\Client;
9
use GarethEllis\Tldr\Fetcher\Exception\RemoteFetcherException;
10
use Metadata\Cache\CacheInterface;
11
12
/**
13
 * Class RemoteFetcher
14
 *
15
 * Fetches a page from the remote repository and optionally caches the result
16
 *
17
 * @package GarethEllis\Tldr\Fetcher
18
 */
19
class RemoteFetcher implements PageFetcherInterface
20
{
21
    use OperatingSystemTrait;
22
23
    protected $http;
24
25
    /**
26
     * @var string The base URL of the JSON index containing a list of commands
27
     */
28
    protected $baseUrl = "https://api.github.com/repos/tldr-pages/tldr/contents/pages/index.json?ref=master";
29
30
    /**
31
     * @var string URL template for fetching an individual page
32
     */
33
    protected $pageInfoUrlTemplate =
34
        "https://api.github.com/repos/tldr-pages/tldr/contents/pages/{platform}/{command}.md?ref=master";
35
36
    /**
37
     * @var array
38
     */
39
    private $options;
40
41
    /**
42
     * RemoteFetcher constructor.
43
     *
44
     * @param \GuzzleHttp\Client $http
45
     * @param CacheInterface $cache
0 ignored issues
show
Bug introduced by
There is no parameter named $cache. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
46
     */
47
    public function __construct(Client $http, array $options = [])
48
    {
49
        $this->http = $http;
50
        $this->options = $options;
51
    }
52
53
    /**
54
     * Fetch a page from remote repository
55
     *
56
     * @param string $pageName
57
     * @return string
58
     * @throws PageNotFoundException
59
     */
60
    public function fetchPage(String $pageName): TldrPage
61
    {
62
        try {
63
            $response = $this->http->get($this->baseUrl);
64
        } catch (\Exception $e) {
65
            throw new RemoteFetcherException($e->getMessage());
66
        }
67
68
        $contents = json_decode($response->getBody()->getContents(), true);
69
        $pages = base64_decode($contents["content"]);
70
        $json = json_decode($pages, true);
71
        $pages = $json["commands"];
72
        $page = $this->findPageInList($pageName, $pages);
73
74
        $url = str_replace("{platform}", $page["platform"], $this->pageInfoUrlTemplate);
75
        $url = str_replace("{command}", $page["name"], $url);
76
77
        try {
78
            $response = $this->http->get($url);
79
        } catch (\Exception $e) {
80
            throw new RemoteFetcherException($e->getMessage());
81
        }
82
83
        $contents = json_decode($response->getBody()->getContents(), true);
84
        $pageContent = base64_decode($contents["content"]);
85
        $page = new TldrPage($pageName, $page["platform"], $pageContent);
86
87
        return $page;
88
    }
89
90
    protected function findPageInList(String $page, array $list)
91
    {
92
        $filtered = array_filter($list, function ($foundPage) use ($page) {
93
            return $foundPage["name"] === $page;
94
        });
95
96
        if (empty($filtered)) {
97
            throw new PageNotFoundException;
98
        }
99
100
        $page = array_shift($filtered);
101
102
        foreach ($page["platform"] as $k => $platform) {
103
104
            if ($platform === $this->getOperatingSystem()) {
105
                $platformSpecificKey = $k;
106
                continue;
107
            }
108
109
            if ($platform === "common") {
110
                $commonKey = $k;
111
                continue;
112
            }
113
        }
114
115
        if (!isset($commonKey) && !isset($platformSpecificKey)) {
116
            throw new PageNotFoundException();
117
        }
118
119
        $key = $platformSpecificKey ?? $commonKey;
0 ignored issues
show
Bug introduced by
The variable $platformSpecificKey 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...
120
        $page["platform"] = $page["platform"][$key];
121
122
        return $page;
123
    }
124
}
125