Obfuscator.php
69 lines
| 1 | <?php |
| 2 | |
| 3 | |
| 4 | class Tribe__Support__Obfuscator { |
| 5 | |
| 6 | /** |
| 7 | * @var array |
| 8 | */ |
| 9 | protected $prefixes = []; |
| 10 | |
| 11 | /** |
| 12 | * Tribe__Support__Obfuscator constructor. |
| 13 | * |
| 14 | * @param array $prefixes |
| 15 | */ |
| 16 | public function __construct( array $prefixes = [] ) { |
| 17 | $this->prefixes = $prefixes; |
| 18 | } |
| 19 | |
| 20 | /** |
| 21 | * Whether a value should be obfuscated or not. |
| 22 | * |
| 23 | * @param string $key |
| 24 | * |
| 25 | * @return bool |
| 26 | */ |
| 27 | public function should_obfuscate( $key ) { |
| 28 | foreach ( $this->prefixes as $prefix ) { |
| 29 | if ( strpos( $key, $prefix ) === 0 ) { |
| 30 | return true; |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | return false; |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * Conditionally obfuscates a string value. |
| 39 | * |
| 40 | * @param string $key |
| 41 | * @param mixed $string_value |
| 42 | * |
| 43 | * @return mixed Either the obfuscated string or the original value if not a string. |
| 44 | */ |
| 45 | public function obfuscate( $key, $string_value ) { |
| 46 | if ( ! is_string( $string_value ) ) { |
| 47 | return $string_value; |
| 48 | } |
| 49 | if ( ! $this->should_obfuscate( $key ) ) { |
| 50 | return $string_value; |
| 51 | } |
| 52 | |
| 53 | $length = strlen( $string_value ); |
| 54 | if ( $length <= 3 ) { |
| 55 | return preg_replace( "/./", "#", $string_value ); |
| 56 | } elseif ( $length > 3 && $length <= 5 ) { |
| 57 | return preg_replace( '/^(.{1}).*$/', '$1' . str_repeat( '#', $length - 1 ) . '$2', $string_value ); |
| 58 | } elseif ( $length > 5 && $length <= 9 ) { |
| 59 | return preg_replace( '/^(.{1}).*(.{1})$/', '$1' . str_repeat( '#', $length - 2 ) . '$2', $string_value ); |
| 60 | } elseif ( $length > 9 && $length <= 19 ) { |
| 61 | return preg_replace( '/^(.{2}).*(.{2})$/', '$1' . str_repeat( '#', $length - 4 ) . '$2', $string_value ); |
| 62 | } elseif ( $length > 19 && $length <= 31 ) { |
| 63 | return preg_replace( '/^(.{3}).*(.{3})$/', '$1' . str_repeat( '#', $length - 6 ) . '$2', $string_value ); |
| 64 | } |
| 65 | |
| 66 | return preg_replace( '/^(.{4}).*(.{4})$/', '$1' . str_repeat( '#', $length - 8 ) . '$2', $string_value ); |
| 67 | } |
| 68 | } |
| 69 |