Test Failed
Push — master ( ca159c...8f4401 )
by Sebastian
03:00
created

PHPFile::findClasses()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * @package Application Utils
4
 * @subpackage FileHelper
5
 * @see \AppUtils\FileHelper\PHPFile
6
 */
7
8
declare(strict_types=1);
9
10
namespace AppUtils\FileHelper;
11
12
use AppUtils\FileHelper;
13
use AppUtils\FileHelper_Exception;
14
use AppUtils\FileHelper_PHPClassInfo;
15
use SplFileInfo;
16
17
/**
18
 * Specialized file information class for PHP files.
19
 *
20
 * Create an instance with {@see PHPFile::factory()}.
21
 *
22
 * @package Application Utils
23
 * @subpackage FileHelper
24
 * @author Sebastian Mordziol <[email protected]>
25
 */
26
class PHPFile extends FileInfo
27
{
28
    /**
29
     * @param string|PathInfoInterface|SplFileInfo $path
30
     * @return PHPFile
31
     * @throws FileHelper_Exception
32
     */
33
    public static function factory($path) : PHPFile
34
    {
35
        if($path instanceof self) {
36
            return $path;
37
        }
38
39
        $instance = self::createInstance($path);
40
41
        if($instance instanceof self) {
42
            return $instance;
43
        }
44
45
        throw new FileHelper_Exception(
46
            'Invalid class.'
47
        );
48
    }
49
50
    /**
51
     * Validates a PHP file's syntax.
52
     *
53
     * NOTE: This will fail silently if the PHP command line
54
     * is not available. Use {@link FileHelper::canMakePHPCalls()}
55
     * to check this beforehand as needed.
56
     *
57
     * @return boolean|string[] A boolean true if the file is valid, an array with validation messages otherwise.
58
     * @throws FileHelper_Exception
59
     */
60
    public function checkSyntax()
61
    {
62
        if(!FileHelper::canMakePHPCalls())
63
        {
64
            return true;
65
        }
66
67
        $output = array();
68
        $command = sprintf('php -l "%s" 2>&1', $this->getPath());
69
        exec($command, $output);
70
71
        // when the validation is successful, the first entry
72
        // in the array contains the success message. When it
73
        // is invalid, the first entry is always empty.
74
        if(!empty($output[0])) {
75
            return true;
76
        }
77
78
        array_shift($output); // the first entry is always empty
79
        array_pop($output); // the last message is a superfluous message saying there's an error
80
81
        return $output;
82
    }
83
84
    public function findClasses() : FileHelper_PHPClassInfo
85
    {
86
        return new FileHelper_PHPClassInfo($this);
87
    }
88
}
89