Passed
Pull Request — master (#315)
by Théo
02:34
created

Php::compactAnnotations()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 45
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 45
rs 9.6666
c 0
b 0
f 0
cc 4
nc 5
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 Exception;
18
use KevinGH\Box\Annotation\Convert\ToString;
19
use KevinGH\Box\Annotation\Dump;
20
use KevinGH\Box\Annotation\Tokenizer;
21
use KevinGH\Box\Annotation\Tokens;
22
use const T_COMMENT;
23
use const T_DOC_COMMENT;
24
use const T_WHITESPACE;
25
use function count;
26
use function in_array;
27
use function is_string;
28
use function preg_replace;
29
use function str_repeat;
30
use function strpos;
31
use function substr_count;
32
use function token_get_all;
33
34
/**
35
 * A PHP source code compactor copied from Composer.
36
 *
37
 * @see https://github.com/composer/composer/blob/a8df30c09be550bffc37ba540fb7c7f0383c3944/src/Composer/Compiler.php#L214
38
 *
39
 * @author Kevin Herrera <[email protected]>
40
 * @author Fabien Potencier <[email protected]>
41
 * @author Jordi Boggiano <[email protected]>
42
 * @author Théo Fidry <[email protected]>
43
 * @private
44
 */
45
final class Php extends FileExtensionCompactor
46
{
47
    private $converter;
48
    private $tokenizer;
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function __construct(Tokenizer $tokenizer, array $extensions = ['php'])
54
    {
55
        parent::__construct($extensions);
56
57
        $this->converter = new ToString();
58
        $this->tokenizer = $tokenizer;
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    protected function compactContent(string $contents): string
65
    {
66
        // TODO: refactor this piece of code
67
        // - strip down blank spaces
68
        // - remove useless spaces
69
        // - strip down comments except Doctrine style annotations unless whitelisted -> BC break to document;
70
        //   Alternatively provide an easy way to strip down all "regular" annotations such as @package, @param
71
        //   & co.
72
        // - completely remove comments & docblocks if empty
73
        // TODO regarding the doc: it current has its own `annotations` entry. Maybe it would be best to
74
        // include it as a sub element of `compactors`
75
        $output = '';
76
77
        foreach (token_get_all($contents) as $token) {
78
            if (is_string($token)) {
79
                $output .= $token;
80
            } elseif (in_array($token[0], [T_COMMENT, T_DOC_COMMENT], true)) {
81
                if ($this->tokenizer && false !== strpos($token[1], '@')) {
82
                    try {
83
                        $output .= $this->compactAnnotations($token[1]);
84
                    } catch (Exception $exception) {
85
                        $output .= $token[1];
86
                    }
87
                } else {
88
                    $output .= str_repeat("\n", substr_count($token[1], "\n"));
89
                }
90
            } elseif (T_WHITESPACE === $token[0]) {
91
                // reduce wide spaces
92
                $whitespace = preg_replace('{[ \t]+}', ' ', $token[1]);
93
94
                // normalize newlines to \n
95
                $whitespace = preg_replace('{(?:\r\n|\r|\n)}', "\n", $whitespace);
96
97
                // trim leading spaces
98
                $whitespace = preg_replace('{\n +}', "\n", $whitespace);
99
100
                $output .= $whitespace;
101
            } else {
102
                $output .= $token[1];
103
            }
104
        }
105
106
        return $output;
107
    }
108
109
    private function compactAnnotations(string $docblock): string
110
    {
111
        $annotations = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $annotations is dead and can be removed.
Loading history...
112
        $index = -1;
0 ignored issues
show
Unused Code introduced by
The assignment to $index is dead and can be removed.
Loading history...
113
        $inside = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $inside is dead and can be removed.
Loading history...
114
        $nodes = $this->tokenizer->parse($docblock);
115
116
        if (0 === $nodes->getChildrenNumber()) {
117
            return str_repeat("\n", substr_count($docblock, "\n"));
118
        }
119
120
//        foreach ($nodes->getChildren() as $child) {
121
//            if ((0 === $inside) && (DocLexer::T_AT === $child[0])) {
122
//                ++$index;
123
//            } elseif (DocLexer::T_OPEN_PARENTHESIS === $child[0]) {
124
//                ++$inside;
125
//            } elseif (DocLexer::T_CLOSE_PARENTHESIS === $child[0]) {
126
//                --$inside;
127
//            }
128
//
129
//            if (!isset($annotations[$index])) {
130
//                $annotations[$index] = [];
131
//            }
132
//
133
//            $annotations[$index][] = $child;
134
//        }
135
136
        $breaks = substr_count($docblock, "\n");
137
        $docblock = '/**';
138
139
        $compacted = (new Dump())->dumpAnnotations($nodes);
140
        foreach ($compacted as $annotation) {
141
            $docblock .= "\n".$annotation;
142
        }
143
144
        $breaks -= count($compacted);
145
146
        if ($breaks > 0) {
147
            $docblock .= str_repeat("\n", $breaks - 1);
148
            $docblock .= "\n*/";
149
        } else {
150
            $docblock .= ' */';
151
        }
152
153
        return $docblock;
154
    }
155
}
156