Issues (32)

Security Analysis    no request data  

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/Highlighter.php (3 issues)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/**
4
 * This file is part of Collision.
5
 *
6
 * (c) Nuno Maduro <[email protected]>
7
 *
8
 *  For the full copyright and license information, please view the LICENSE
9
 *  file that was distributed with this source code.
10
 */
11
12
namespace NunoMaduro\Collision;
13
14
use NunoMaduro\Collision\Contracts\Highlighter as HighlighterContract;
15
16
/**
17
 * This is an Collision Highlighter implementation.
18
 *
19
 * Code originally from { JakubOnderka\\PhpConsoleColor }. But the package got deprecated.
20
 *
21
 * @internal
22
 *
23
 * @final
24
 */
25
class Highlighter implements HighlighterContract
26
{
27
    /**
28
     * Holds the theme.
29
     *
30
     * @var array
31
     */
32
    private $theme = [
33
        self::TOKEN_STRING     => ['light_gray'],
34
        self::TOKEN_COMMENT    => ['dark_gray', 'italic'],
35
        self::TOKEN_KEYWORD    => ['magenta', 'bold'],
36
        self::TOKEN_DEFAULT    => ['default', 'bold'],
37
        self::TOKEN_HTML       => ['blue', 'bold'],
38
        self::ACTUAL_LINE_MARK => ['red', 'bold'],
39
        self::LINE_NUMBER      => ['dark_gray'],
40
    ];
41
42
    const TOKEN_DEFAULT = 'token_default';
43
    const TOKEN_COMMENT = 'token_comment';
44
    const TOKEN_STRING  = 'token_string';
45
    const TOKEN_HTML    = 'token_html';
46
    const TOKEN_KEYWORD = 'token_keyword';
47
48
    const ACTUAL_LINE_MARK = 'actual_line_mark';
49
    const LINE_NUMBER      = 'line_number';
50
51
    /** @var ConsoleColor */
52
    private $color;
53
54
    /** @var array */
55
    private $defaultTheme = [
56
        self::TOKEN_STRING  => 'red',
57
        self::TOKEN_COMMENT => 'yellow',
58
        self::TOKEN_KEYWORD => 'green',
59
        self::TOKEN_DEFAULT => 'default',
60
        self::TOKEN_HTML    => 'cyan',
61
62
        self::ACTUAL_LINE_MARK => 'red',
63
        self::LINE_NUMBER      => 'dark_gray',
64
    ];
65
66
    /**
67
     * Creates an instance of the Highlighter.
68
     */
69 13
    public function __construct(ConsoleColor $color = null)
70
    {
71 13
        $this->color = $color ?: new ConsoleColor();
72
73 13
        foreach ($this->defaultTheme as $name => $styles) {
74 13
            if (!$this->color->hasTheme($name)) {
75 13
                $this->color->addTheme($name, $styles);
76
            }
77
        }
78
79 13
        foreach ($this->theme as $name => $styles) {
80 13
            $this->color->addTheme((string) $name, $styles);
81
        }
82 13
    }
83
84
    /**
85
     * {@inheritdoc}
86
     */
87 4
    public function highlight(string $content, int $line): string
88
    {
89 4
        return rtrim($this->getCodeSnippet($content, $line, 4, 4));
90
    }
91
92
    /**
93
     * @param string $source
94
     * @param int    $lineNumber
95
     * @param int    $linesBefore
96
     * @param int    $linesAfter
97
     *
98
     * @return string
99
     */
100 4
    public function getCodeSnippet($source, $lineNumber, $linesBefore = 2, $linesAfter = 2)
101
    {
102 4
        $tokenLines = $this->getHighlightedLines($source);
103
104 4
        $offset     = $lineNumber - $linesBefore - 1;
105 4
        $offset     = max($offset, 0);
106 4
        $length     = $linesAfter + $linesBefore + 1;
107 4
        $tokenLines = array_slice($tokenLines, $offset, $length, $preserveKeys = true);
108
109 4
        $lines = $this->colorLines($tokenLines);
110
111 4
        return $this->lineNumbers($lines, $lineNumber);
112
    }
113
114
    /**
115
     * @param string $source
116
     *
117
     * @return array
118
     */
119 4
    private function getHighlightedLines($source)
120
    {
121 4
        $source = str_replace(["\r\n", "\r"], "\n", $source);
122 4
        $tokens = $this->tokenize($source);
123
124 4
        return $this->splitToLines($tokens);
125
    }
126
127
    /**
128
     * @param string $source
129
     *
130
     * @return array
131
     */
132 4
    private function tokenize($source)
133
    {
134 4
        $tokens = token_get_all($source);
135
136 4
        $output      = [];
137 4
        $currentType = null;
138 4
        $buffer      = '';
139
140 4
        foreach ($tokens as $token) {
141 4
            if (is_array($token)) {
142 4
                switch ($token[0]) {
143 4
                    case T_WHITESPACE:
144 4
                        break;
145
146 4
                    case T_OPEN_TAG:
147 4
                    case T_OPEN_TAG_WITH_ECHO:
148 4
                    case T_CLOSE_TAG:
149 4
                    case T_STRING:
150 4
                    case T_VARIABLE:
151
152
                        // Constants
153 4
                    case T_DIR:
154 4
                    case T_FILE:
155 4
                    case T_METHOD_C:
156 4
                    case T_DNUMBER:
157 4
                    case T_LNUMBER:
158 4
                    case T_NS_C:
159 4
                    case T_LINE:
160 4
                    case T_CLASS_C:
161 4
                    case T_FUNC_C:
162 4
                    case T_TRAIT_C:
163 4
                        $newType = self::TOKEN_DEFAULT;
164 4
                        break;
165
166 4
                    case T_COMMENT:
167 4
                    case T_DOC_COMMENT:
168 1
                        $newType = self::TOKEN_COMMENT;
169 1
                        break;
170
171 4
                    case T_ENCAPSED_AND_WHITESPACE:
172 4
                    case T_CONSTANT_ENCAPSED_STRING:
173 4
                        $newType = self::TOKEN_STRING;
174 4
                        break;
175
176 4
                    case T_INLINE_HTML:
177
                        $newType = self::TOKEN_HTML;
178
                        break;
179
180
                    default:
181 4
                        $newType = self::TOKEN_KEYWORD;
182
                }
183
            } else {
184 4
                $newType = $token === '"' ? self::TOKEN_STRING : self::TOKEN_KEYWORD;
185
            }
186
187 4
            if ($currentType === null) {
188 4
                $currentType = $newType;
0 ignored issues
show
The variable $newType does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
189
            }
190
191 4
            if ($currentType !== $newType) {
192 4
                $output[]    = [$currentType, $buffer];
193 4
                $buffer      = '';
194 4
                $currentType = $newType;
195
            }
196
197 4
            $buffer .= is_array($token) ? $token[1] : $token;
198
        }
199
200 4
        if (isset($newType)) {
201 4
            $output[] = [$newType, $buffer];
202
        }
203
204 4
        return $output;
205
    }
206
207
    /**
208
     * @return array
209
     */
210 4
    private function splitToLines(array $tokens)
211
    {
212 4
        $lines = [];
213
214 4
        $line = [];
215 4
        foreach ($tokens as $token) {
216 4
            foreach (explode("\n", $token[1]) as $count => $tokenLine) {
217 4
                if ($count > 0) {
218 4
                    $lines[] = $line;
219 4
                    $line    = [];
220
                }
221
222 4
                if ($tokenLine === '') {
223 4
                    continue;
224
                }
225
226 4
                $line[] = [$token[0], $tokenLine];
227
            }
228
        }
229
230 4
        $lines[] = $line;
231
232 4
        return $lines;
233
    }
234
235
    /**
236
     * @return array
237
     */
238 4
    private function colorLines(array $tokenLines)
239
    {
240 4
        $lines = [];
241 4
        foreach ($tokenLines as $lineCount => $tokenLine) {
242 4
            $line = '';
243 4
            foreach ($tokenLine as $token) {
244 4
                [$tokenType, $tokenValue] = $token;
0 ignored issues
show
The variable $tokenType does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
The variable $tokenValue does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
245 4
                if ($this->color->hasTheme($tokenType)) {
246 4
                    $line .= $this->color->apply($tokenType, $tokenValue);
247
                } else {
248 4
                    $line .= $tokenValue;
249
                }
250
            }
251 4
            $lines[$lineCount] = $line;
252
        }
253
254 4
        return $lines;
255
    }
256
257
    /**
258
     * @param int|null $markLine
259
     *
260
     * @return string
261
     */
262 4
    private function lineNumbers(array $lines, $markLine = null)
263
    {
264 4
        end($lines);
265 4
        $lineStrlen = strlen(key($lines) + 1);
266
267 4
        $snippet = '';
268 4
        foreach ($lines as $i => $line) {
269 4
            if ($markLine !== null) {
270 4
                $snippet .= ($markLine === $i + 1 ? $this->color->apply(self::ACTUAL_LINE_MARK, '  > ') : '    ');
271
            }
272
273 4
            $snippet .= $this->color->apply(self::LINE_NUMBER, str_pad($i + 1, $lineStrlen, ' ', STR_PAD_LEFT) . '| ');
274 4
            $snippet .= $line . PHP_EOL;
275
        }
276
277 4
        return $snippet;
278
    }
279
}
280