Passed
Push — master ( 69774c...de7969 )
by Sebastian
02:46
created

Linting   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 4
eloc 12
c 3
b 0
f 0
dl 0
loc 39
ccs 13
cts 13
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A hasSyntaxErrors() 0 6 1
A execute() 0 13 3
1
<?php
2
3
/**
4
 * This file is part of CaptainHook
5
 *
6
 * (c) Sebastian Feldmann <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace CaptainHook\App\Hook\PHP\Action;
13
14
use CaptainHook\App\Config;
15
use CaptainHook\App\Console\IO;
16
use CaptainHook\App\Exception\ActionFailed;
17
use CaptainHook\App\Hook\Action;
18
use SebastianFeldmann\Cli\Processor\ProcOpen as Processor;
19
use SebastianFeldmann\Git\Repository;
20
21
/**
22
 * Class Linter
23
 *
24
 * @package CaptainHook
25
 * @author  Sebastian Feldmann <[email protected]>
26
 * @link    https://github.com/captainhookphp/captainhook
27
 * @since   Class available since Release 1.0.5
28
 */
29
class Linting implements Action
30
{
31
    /**
32
     * Executes the action
33
     *
34
     * @param  \CaptainHook\App\Config           $config
35
     * @param  \CaptainHook\App\Console\IO       $io
36
     * @param  \SebastianFeldmann\Git\Repository $repository
37
     * @param  \CaptainHook\App\Config\Action    $action
38
     * @return void
39 2
     * @throws \Exception
40
     */
41 2
    public function execute(Config $config, IO $io, Repository $repository, Config\Action $action): void
42
    {
43 2
        $changedPHPFiles = $repository->getIndexOperator()->getStagedFilesOfType('php');
44 2
45 2
        $io->write('linting files:', true, IO::VERBOSE);
46 2
        foreach ($changedPHPFiles as $file) {
47 2
            $io->write('  - ' . $file, true, IO::VERBOSE);
48
            if ($this->hasSyntaxErrors($file)) {
49
                $io->write('    syntax error detected in ' . $file, true, IO::VERBOSE);
50 1
                throw new ActionFailed('linting failed: PHP syntax errors in ' . $file);
51 1
            }
52
        }
53
        $io->write('<info>No syntax errors detected</info>');
54
    }
55
56
    /**
57
     * Lint a php file
58
     *
59 2
     * @param  string $file
60
     * @return bool
61 2
     */
62 2
    protected function hasSyntaxErrors($file): bool
63
    {
64 2
        $process = new Processor();
65
        $result  = $process->run('php -l ' . escapeshellarg($file));
66
67
        return !$result->isSuccessful();
68
    }
69
}
70