1<?php 2/** 3 * This file is part of the FreeDSx LDAP package. 4 * 5 * (c) Chad Sikorra <Chad.Sikorra@gmail.com> 6 * 7 * For the full copyright and license information, please view the LICENSE 8 * file that was distributed with this source code. 9 */ 10 11namespace FreeDSx\Ldap\Entry; 12 13/** 14 * Some common methods around escaping attribute values and RDN values. 15 * 16 * @author Chad Sikorra <Chad.Sikorra@gmail.com> 17 */ 18trait EscapeTrait 19{ 20 /** 21 * Escape all characters in a value. 22 * 23 * @param string $value 24 * @return string 25 */ 26 public static function escapeAll(string $value): string 27 { 28 if (self::shouldNotEscape($value)) { 29 return $value; 30 } 31 32 return '\\' . \implode('\\', \str_split(\bin2hex($value), 2)); 33 } 34 35 /** 36 * Replace non-printable ASCII with escaped hex. 37 */ 38 protected static function escapeNonPrintable(string $value): string 39 { 40 return (string) \preg_replace_callback('/([\x00-\x1F\x7F])/', function ($matches) { 41 return '\\' . \bin2hex($matches[1]); 42 }, $value); 43 } 44 45 protected static function shouldNotEscape(string $value): bool 46 { 47 return (\preg_match('/^(\\\\[0-9A-Fa-f]{2})+$/', $value) === 1 || $value === ''); 48 } 49} 50