Completed
Pull Request — master (#2)
by Sullivan
02:00
created

Linter::validate()   B

Complexity

Conditions 6
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 16
rs 8.8571
cc 6
eloc 9
nc 2
nop 1
1
<?php
2
3
namespace SLLH\ComposerLint;
4
5
use Composer\Json\JsonFile;
6
7
/**
8
 * @author Sullivan Senechal <[email protected]>
9
 */
10
final class Linter
11
{
12
    /**
13
     * @var array
14
     */
15
    private $manifest;
16
17
    /**
18
     * @param string $file composer.json file path
19
     *
20
     * @return string[]
21
     */
22
    public function validate($file)
23
    {
24
        $errors = array();
25
        $json = new JsonFile($file);
26
        $this->manifest = $json->read();
0 ignored issues
show
Documentation Bug introduced by
It seems like $json->read() of type * is incompatible with the declared type array of property $manifest.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
27
28
        if (isset($this->manifest['config']['sort-packages']) && $this->manifest['config']['sort-packages']) {
29
            foreach (array('require', 'require-dev', 'conflict', 'replace', 'provide', 'suggest') as $linksSection) {
30
                if (array_key_exists($linksSection, $this->manifest) && !$this->packagesAreSorted($this->manifest[$linksSection])) {
31
                    array_push($errors, 'Links under '.$linksSection.' section are not sorted.');
32
                }
33
            }
34
        }
35
36
        return $errors;
37
    }
38
39
    private function packagesAreSorted(array $packages)
40
    {
41
        $names = array_keys($packages);
42
43
        $hasPHP = in_array('php', $names);
44
        $extNames = array_filter($names, function ($name) {
45
            return 'ext-' === substr($name, 0, 4) && !strstr($name, '/');
46
        });
47
        sort($extNames);
48
        $vendorName = array_filter($names, function ($name) {
49
            return 'ext-' !== substr($name, 0, 4) && 'php' !== $name;
50
        });
51
        sort($vendorName);
52
53
        $sortedNames = array_merge(
54
            $hasPHP ? array('php') : array(),
55
            $extNames,
56
            $vendorName
57
        );
58
59
        return $sortedNames === $names;
60
    }
61
}
62