| 1 |
<?php |
| 2 |
|
| 3 |
namespace WP_Defender\Component\Scan; |
| 4 |
|
| 5 |
use WP_Defender\Component; |
| 6 |
|
| 7 |
class Tokens extends Component { |
| 8 |
public static $tokens = []; |
| 9 |
|
| 10 |
/** |
| 11 |
* @param $line |
| 12 |
* |
| 13 |
* @return array |
| 14 |
*/ |
| 15 |
public static function get_tokens_by_line( $line ) { |
| 16 |
$catch = []; |
| 17 |
foreach ( self::$tokens as $token ) { |
| 18 |
if ( $line === $token['line'] ) { |
| 19 |
$catch[] = $token; |
| 20 |
} |
| 21 |
} |
| 22 |
|
| 23 |
return $catch; |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* @param $tokens |
| 28 |
* |
| 29 |
* @return string |
| 30 |
*/ |
| 31 |
public static function formatter( $tokens ) { |
| 32 |
$string = ''; |
| 33 |
foreach ( $tokens as $token ) { |
| 34 |
$string .= $token['content']; |
| 35 |
} |
| 36 |
|
| 37 |
return $string; |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* @param $content |
| 42 |
* @param $offset |
| 43 |
* |
| 44 |
* @return int |
| 45 |
*/ |
| 46 |
public static function get_line_from_offset( $content, $offset ) { |
| 47 |
[$before] = str_split( $content, $offset ); |
| 48 |
$line_number = strlen( $before ) - strlen( str_replace( PHP_EOL, "", $before ) ) + 1; |
| 49 |
|
| 50 |
return $line_number; |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* Get a list of [line,column] of each token, we will need to use this |
| 55 |
* for highlight the code on frontend |
| 56 |
* |
| 57 |
* @param array $tokens |
| 58 |
* |
| 59 |
* @return array |
| 60 |
*/ |
| 61 |
public static function get_offsets_map( $tokens = [] ) { |
| 62 |
$tmp = []; |
| 63 |
$mapper = []; |
| 64 |
foreach ( $tokens as $token ) { |
| 65 |
$tmp[ $token['line'] ][] = $token['column'] + $token['length']; |
| 66 |
} |
| 67 |
foreach ( $tmp as $line => &$cols ) { |
| 68 |
sort( $cols ); |
| 69 |
$start = count( $cols ) > 1 ? current( $cols ) : 0; |
| 70 |
$range = [ $start, end( $cols ) ]; |
| 71 |
$mapper[] = [ |
| 72 |
'line' => $line, |
| 73 |
'range' => $range |
| 74 |
]; |
| 75 |
} |
| 76 |
|
| 77 |
return $mapper; |
| 78 |
} |
| 79 |
} |
| 80 |
|