Completed
Push — master ( aa9657...bb9832 )
by Sebastian
05:21
created

Linting::hasSyntaxErrors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
crap 1
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\Hook\Action;
16
use SebastianFeldmann\Cli\Processor\ProcOpen as Processor;
17
use SebastianFeldmann\Git\Repository;
18
19
/**
20
 * Class Linter
21
 *
22
 * @package CaptainHook
23
 * @author  Sebastian Feldmann <[email protected]>
24
 * @link    https://github.com/sebastianfeldmann/captainhook
25
 * @since   Class available since Release 1.0.5
26
 */
27
class Linting implements Action
28
{
29
    /**
30
     * Executes the action.
31
     *
32
     * @param  \SebastianFeldmann\CaptainHook\Config         $config
33
     * @param  \SebastianFeldmann\CaptainHook\Console\IO     $io
34
     * @param  \SebastianFeldmann\Git\Repository             $repository
35
     * @param  \SebastianFeldmann\CaptainHook\Config\Action  $action
36
     * @throws \Exception
37
     */
38
    public function execute(Config $config, IO $io, Repository $repository, Config\Action $action)
39 2
    {
40
        $changedPHPFiles = $repository->getIndexOperator()->getStagedFilesOfType('php');
41 2
42
        $io->write('linting files:', true, IO::VERBOSE);
43 2
        foreach ($changedPHPFiles as $file) {
44 2
            $io->write('  - ' . $file, true, IO::VERBOSE);
45 2
            if ($this->hasSyntaxErrors($file)) {
46 2
                throw ActionFailed::withMessage('syntax errors in file: ' . $file);
47 2
            }
48
        }
49
        $io->write('<info>no syntax errors detected</info>');
50 1
    }
51 1
52
    /**
53
     * Lint a php file.
54
     *
55
     * @param  string $file
56
     * @return bool
57
     */
58
    protected function hasSyntaxErrors($file) : bool
59 2
    {
60
        $process = new Processor();
61 2
        $result  = $process->run('php -l ' . escapeshellarg($file));
62 2
63 2
        return !$result->isSuccessful();
64
    }
65
}
66