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

Linter   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
c 1
b 0
f 0
lcom 1
cbo 1
dl 0
loc 45
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B validate() 0 16 6
A packagesAreSorted() 0 15 2
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 correctly.');
32
                }
33
            }
34
        }
35
36
        return $errors;
37
    }
38
39
    private function packagesAreSorted(array $packages)
40
    {
41
        $names = array_keys($packages);
42
        $sortedNames = $names;
43
        usort($sortedNames, function ($name1, $name2) {
44
            if ('php' === $name2) {
45
                return 1;
46
            }
47
            // TODO: ext-*
48
49
            return strcmp($name1, $name2);
50
        });
51
52
        return $sortedNames === $names;
53
    }
54
}
55