Passed
Pull Request — master (#22)
by Théo
02:53
created

Php::compactContent()   C

Complexity

Conditions 8
Paths 7

Size

Total Lines 34
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 20
nc 7
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the box project.
7
 *
8
 * (c) Kevin Herrera <[email protected]>
9
 *     Théo Fidry <[email protected]>
10
 *
11
 * This source file is subject to the MIT license that is bundled
12
 * with this source code in the file LICENSE.
13
 */
14
15
namespace KevinGH\Box\Compactor;
16
17
use Doctrine\Common\Annotations\DocLexer;
18
use Exception;
19
use Herrera\Annotations\Convert\ToString;
20
use Herrera\Annotations\Tokenizer;
21
use Herrera\Annotations\Tokens;
22
23
/**
24
 * A PHP source code compactor copied from Composer.
25
 *
26
 * @author Kevin Herrera <[email protected]>
27
 * @author Fabien Potencier <[email protected]>
28
 * @author Jordi Boggiano <[email protected]>
29
 *
30
 * @see https://github.com/composer/composer/blob/a8df30c09be550bffc37ba540fb7c7f0383c3944/src/Composer/Compiler.php#L214
31
 */
32
final class Php extends FileExtensionCompactor
33
{
34
    private $converter;
35
    private $tokenizer;
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function __construct(Tokenizer $tokenizer, array $extensions = ['php'])
41
    {
42
        parent::__construct($extensions);
43
44
        $this->converter = new ToString();
45
        $this->tokenizer = $tokenizer;
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    protected function compactContent(string $contents): string
52
    {
53
        $output = '';
54
55
        foreach (token_get_all($contents) as $token) {
56
            if (is_string($token)) {
57
                $output .= $token;
58
            } elseif (in_array($token[0], [T_COMMENT, T_DOC_COMMENT], true)) {
59
                if ($this->tokenizer && (false !== strpos($token[1], '@'))) {
60
                    try {
61
                        $output .= $this->compactAnnotations($token[1]);
62
                    } catch (Exception $exception) {
63
                        $output .= $token[1];
64
                    }
65
                } else {
66
                    $output .= str_repeat("\n", substr_count($token[1], "\n"));
67
                }
68
            } elseif (T_WHITESPACE === $token[0]) {
69
                // reduce wide spaces
70
                $whitespace = preg_replace('{[ \t]+}', ' ', $token[1]);
71
72
                // normalize newlines to \n
73
                $whitespace = preg_replace('{(?:\r\n|\r|\n)}', "\n", $whitespace);
74
75
                // trim leading spaces
76
                $whitespace = preg_replace('{\n +}', "\n", $whitespace);
77
78
                $output .= $whitespace;
79
            } else {
80
                $output .= $token[1];
81
            }
82
        }
83
84
        return $output;
85
    }
86
87
    private function compactAnnotations(string $docblock): string
88
    {
89
        $annotations = [];
90
        $index = -1;
91
        $inside = 0;
92
        $tokens = $this->tokenizer->parse($docblock);
93
94
        if (empty($tokens)) {
95
            return str_repeat("\n", substr_count($docblock, "\n"));
96
        }
97
98
        foreach ($tokens as $token) {
99
            if ((0 === $inside) && (DocLexer::T_AT === $token[0])) {
100
                ++$index;
101
            } elseif (DocLexer::T_OPEN_PARENTHESIS === $token[0]) {
102
                ++$inside;
103
            } elseif (DocLexer::T_CLOSE_PARENTHESIS === $token[0]) {
104
                --$inside;
105
            }
106
107
            if (!isset($annotations[$index])) {
108
                $annotations[$index] = [];
109
            }
110
111
            $annotations[$index][] = $token;
112
        }
113
114
        $breaks = substr_count($docblock, "\n");
115
        $docblock = '/**';
116
117
        foreach ($annotations as $annotation) {
118
            $annotation = new Tokens($annotation);
119
            $docblock .= "\n".$this->converter->convert($annotation);
120
        }
121
122
        $breaks -= count($annotations);
123
124
        if ($breaks > 0) {
125
            $docblock .= str_repeat("\n", $breaks - 1);
126
            $docblock .= "\n*/";
127
        } else {
128
            $docblock .= ' */';
129
        }
130
131
        return $docblock;
132
    }
133
}
134