Completed
Push — master ( 22f05c...d80e61 )
by Sebastian
02:41
created

Linting::execute()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 6
nc 3
nop 4
crap 3
1
<?php
2
/**
3
 * This file is part of CaptainHook.
4
 *
5
 * (c) Sebastian Feldmann <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace sebastianfeldmann\CaptainHook\Hook\PHP\Action;
11
12
use sebastianfeldmann\CaptainHook\Config;
13
use sebastianfeldmann\CaptainHook\Console\IO;
14
use sebastianfeldmann\CaptainHook\Exception\ActionFailed;
15
use sebastianfeldmann\CaptainHook\Git\Repository;
16
use sebastianfeldmann\CaptainHook\Hook\Action;
17
use Symfony\Component\Process\Process;
18
use Symfony\Component\Process\ProcessUtils;
19
20
/**
21
 * Class Linter
22
 *
23
 * @package CaptainHook
24
 * @author  Sebastian Feldmann <[email protected]>
25
 * @link    https://github.com/sebastianfeldmann/captainhook
26
 * @since   Class available since Release 1.0.5
27
 */
28
class Linting implements Action
29
{
30
    /**
31
     * Executes the action.
32
     *
33
     * @param  \sebastianfeldmann\CaptainHook\Config         $config
34
     * @param  \sebastianfeldmann\CaptainHook\Console\IO     $io
35
     * @param  \sebastianfeldmann\CaptainHook\Git\Repository $repository
36
     * @param  \sebastianfeldmann\CaptainHook\Config\Action  $action
37
     * @throws \Exception
38
     */
39 2
    public function execute(Config $config, IO $io, Repository $repository, Config\Action $action)
40
    {
41 2
        $changedPHPFiles = $repository->getChangedFilesResolver()->getChangedFilesOfType('php');
42
43 2
        foreach ($changedPHPFiles as $file) {
44 2
            if ($this->hasSyntaxErrors($file)) {
45 2
                throw ActionFailed::withMessage('syntax errors in file: ' . $file);
46
            }
47
        }
48 1
        $io->write('<info>no syntax errors detected</info>');
49 1
    }
50
51
    /**
52
     * Lint a php file.
53
     *
54
     * @param  string $file
55
     * @return bool
56
     */
57 2
    protected function hasSyntaxErrors($file)
58
    {
59 2
        $process = new Process('php -l ' . ProcessUtils::escapeArgument($file));
60 2
        $process->setTimeout(null);
61 2
        $process->run();
62
63 2
        return !$process->isSuccessful();
64
    }
65
}
66