Completed
Push — master ( dcddf7...d2fb4d )
by Théo
05:16 queued 03:22
created

PhpScoper   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 65%

Importance

Changes 0
Metric Value
dl 0
loc 60
ccs 13
cts 20
cp 0.65
rs 10
c 0
b 0
f 0
wmc 6
lcom 1
cbo 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A scope() 0 17 2
A isPhpFile() 0 14 3
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the humbug/php-scoper package.
7
 *
8
 * Copyright (c) 2017 Théo FIDRY <[email protected]>,
9
 *                    Pádraic Brady <[email protected]>
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace Humbug\PhpScoper\Scoper;
16
17
use Humbug\PhpScoper\Scoper;
18
use PhpParser\Error as PhpParserError;
19
use PhpParser\Parser;
20
use PhpParser\PrettyPrinter\Standard;
21
22
final class PhpScoper implements Scoper
23
{
24
    /** @internal */
25
    const FILE_PATH_PATTERN = '/.*\.php$/';
26
    /** @internal */
27
    const NOT_FILE_BINARY = '/\..+?$/';
28
    /** @internal */
29
    const PHP_BINARY = '/^#!.+?php.*\n{1,}<\?php/';
30
31
    private $parser;
32
    private $decoratedScoper;
33
    private $traverserFactory;
34
35 3
    public function __construct(Parser $parser, Scoper $decoratedScoper)
36
    {
37 3
        $this->parser = $parser;
38 3
        $this->decoratedScoper = $decoratedScoper;
39 3
        $this->traverserFactory = new TraverserFactory();
40
    }
41
42
    /**
43
     * Scopes PHP files.
44
     *
45
     * {@inheritdoc}
46
     *
47
     * @throws PhpParserError
48
     */
49 2
    public function scope(string $filePath, string $prefix, array $patchers, array $whitelist, callable $globalWhitelister): string
50
    {
51 2
        if (false === $this->isPhpFile($filePath)) {
52 2
            return $this->decoratedScoper->scope($filePath, $prefix, $patchers, $whitelist, $globalWhitelister);
53
        }
54
55
        $content = file_get_contents($filePath);
56
57
        $traverser = $this->traverserFactory->create($prefix, $whitelist, $globalWhitelister);
58
59
        $statements = $this->parser->parse($content);
60
        $statements = $traverser->traverse($statements);
61
62
        $prettyPrinter = new Standard();
63
64
        return $prettyPrinter->prettyPrintFile($statements)."\n";
65
    }
66
67 2
    private function isPhpFile(string $filePath): bool
68
    {
69 2
        if (1 === preg_match(self::FILE_PATH_PATTERN, $filePath)) {
70
            return true;
71
        }
72
73 2
        if (1 === preg_match(self::NOT_FILE_BINARY, basename($filePath))) {
74 1
            return false;
75
        }
76
77 1
        $content = file_get_contents($filePath);
78
79 1
        return 1 === preg_match(self::PHP_BINARY, $content);
80
    }
81
}
82