GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Pull Request — master (#22)
by joseph
02:08
created

LinksChecker::main()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 13
nc 5
nop 1
dl 0
loc 19
rs 9.2
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace EdmondsCommerce\PHPQA\Markdown;
4
5
use EdmondsCommerce\PHPQA\Helper;
6
7
class LinksChecker
8
{
9
    /**
10
     * @param string $projectRootDirectory
11
     *
12
     * @return array
13
     * @SuppressWarnings(PHPMD.StaticAccess)
14
     */
15
    private static function getFiles(string $projectRootDirectory): array
16
    {
17
        $files   = self::getDocsFiles($projectRootDirectory);
18
        $files[] = self::getMainReadme($projectRootDirectory);
19
20
        return $files;
21
    }
22
23
    /**
24
     * @param string $projectRootDirectory
25
     *
26
     * @return string
27
     * @SuppressWarnings(PHPMD.StaticAccess)
28
     */
29
    private static function getMainReadme(string $projectRootDirectory): string
30
    {
31
        $path = $projectRootDirectory.'/README.md';
32
        if (!is_file($path)) {
33
            throw new \RuntimeException(
34
                "\n\nYou have no README.md file in your project"
35
                ."\n\nAs the bear minimum you need to have this file to pass QA"
36
            );
37
        }
38
39
        return $path;
40
    }
41
42
    /**
43
     * @param string $projectRootDirectory
44
     *
45
     * @return array
46
     * @SuppressWarnings(PHPMD.StaticAccess)
47
     */
48
    private static function getDocsFiles(string $projectRootDirectory): array
49
    {
50
        $files = [];
51
        $dir   = $projectRootDirectory.'/docs';
52
        if (!is_dir($dir)) {
53
            return $files;
54
        }
55
        $directory = new \RecursiveDirectoryIterator($dir);
56
        $recursive = new \RecursiveIteratorIterator($directory);
57
        $regex     = new \RegexIterator(
58
            $recursive,
59
            '/^.+\.md/i',
60
            \RecursiveRegexIterator::GET_MATCH
61
        );
62
        foreach ($regex as $file) {
63
            if (!empty($file[0])) {
64
                $files[] = $file[0];
65
            }
66
        }
67
68
        return $files;
69
    }
70
71
    /**
72
     * @param string $file
73
     *
74
     * @return array
75
     * @SuppressWarnings(PHPMD.StaticAccess)
76
     */
77
    private static function getLinks(string $file): array
78
    {
79
        $links    = [];
80
        $contents = file_get_contents($file);
81
        if (preg_match_all(
82
            '/\[(.+?)\].*?\((.+?)\)/',
83
            $contents,
84
            $matches,
85
            PREG_SET_ORDER
86
        )) {
87
            $links = array_merge($links, $matches);
88
        }
89
90
        return $links;
91
    }
92
93
    /**
94
     * @param string $projectRootDirectory
95
     * @param array  $link
96
     * @param string $file
97
     * @param array  $errors
98
     * @param int    $return
99
     *
100
     * @SuppressWarnings(PHPMD.StaticAccess)
101
     */
102
    private static function checkLink(
103
        string $projectRootDirectory,
104
        array $link,
105
        string $file,
106
        array &$errors,
107
        int &$return
108
    ) {
109
        $path = \trim($link[2]);
110
        if (0 === \strpos($path, '#')) {
111
            return;
112
        }
113
        if (\preg_match('%^(http|//)%', $path)) {
114
            return self::validateHttpLink($link, $errors, $return);
0 ignored issues
show
Bug introduced by
Are you sure the usage of self::validateHttpLink($link, $errors, $return) targeting EdmondsCommerce\PHPQA\Ma...ker::validateHttpLink() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
115
        }
116
117
        $path  = \current(\explode('#', $path, 2));
118
        $start = \rtrim($projectRootDirectory, '/');
119
        if ($path[0] !== '/' || 0 === \strpos($path, './')) {
120
            $relativeSubdirs = \preg_replace(
121
                '%^'.$projectRootDirectory.'%',
122
                '',
123
                \dirname($file)
124
            );
125
            $start           .= '/'.\rtrim($relativeSubdirs, '/');
126
        }
127
        $realpath = \realpath($start.'/'.$path);
128
        if (empty($realpath) || (!\file_exists($realpath) && !\is_dir($realpath))) {
129
            $errors[] = \sprintf("\nBad link for \"%s\" to \"%s\"\n", $link[1], $link[2]);
130
            $return   = 1;
131
        }
132
    }
133
134
135
    /**
136
     * @param string|null $projectRootDirectory
137
     *
138
     * @return int
139
     * @throws \Exception
140
     * @SuppressWarnings(PHPMD.StaticAccess)
141
     */
142
    public static function main(string $projectRootDirectory = null): int
143
    {
144
        $return               = 0;
145
        $projectRootDirectory = $projectRootDirectory ?? Helper::getProjectRootDirectory();
146
        $files                = static::getFiles($projectRootDirectory);
147
        foreach ($files as $file) {
148
            $relativeFile = str_replace($projectRootDirectory, '', $file);
149
            $title        = "\n$relativeFile\n".str_repeat('-', strlen($relativeFile))."\n";
150
            $errors       = [];
151
            $links        = static::getLinks($file);
152
            foreach ($links as $link) {
153
                static::checkLink($projectRootDirectory, $link, $file, $errors, $return);
154
            }
155
            if (!empty($errors)) {
156
                echo $title.implode('', $errors);
157
            }
158
        }
159
160
        return $return;
161
    }
162
163
    private static function validateHttpLink(array $link, array &$errors, int &$return)
164
    {
165
        list(, $anchor, $link) = $link;
166
        $context = stream_context_create(['http' => ['method' => 'HEAD']]);
167
        $result  = null;
168
        try {
169
            $handle = fopen($link, 'rb', false, $context);
170
            $result = stream_get_meta_data($handle);
0 ignored issues
show
Bug introduced by
It seems like $handle can also be of type false; however, parameter $stream of stream_get_meta_data() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

170
            $result = stream_get_meta_data(/** @scrutinizer ignore-type */ $handle);
Loading history...
171
            foreach ($result['wrapper_data'] as $header) {
172
                if (false !== strpos($header, ' 200 ')) {
173
                    return;
174
                }
175
            }
176
        } catch (\Throwable $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
177
        }
178
        $errors[] = \sprintf(
179
            "\nBad link for \"%s\" to \"%s\"\nresult: %s\n",
180
            $anchor,
181
            $link,
182
            var_export($result, true)
183
        );
184
        $return   = 1;
185
    }
186
}
187