diff --git a/src/Lib/SqlEscapingTrait.php b/src/Lib/SqlEscapingTrait.php new file mode 100644 index 0000000..6c6f347 --- /dev/null +++ b/src/Lib/SqlEscapingTrait.php @@ -0,0 +1,45 @@ + '\\\\', + "\0" => '\\0', + "\n" => '\\n', + "\r" => '\\r', + "'" => "\\'", + '"' => '\\"', + "\x1a" => '\\Z', + ] + ); + } + + protected static function quoteSqlString(string $value): string { + return "'" . self::escapeSqlString($value) . "'"; + } + + protected function sqlEscape(string $value): string { + return self::escapeSqlString($value); + } + + protected function quote(string $value): string { + return self::quoteSqlString($value); + } + + protected function escapeString(string $value): string { + return self::escapeSqlString($value); + } +} diff --git a/test/BuddyCore/Lib/SqlEscapingTraitTest.php b/test/BuddyCore/Lib/SqlEscapingTraitTest.php new file mode 100644 index 0000000..d5e98b7 --- /dev/null +++ b/test/BuddyCore/Lib/SqlEscapingTraitTest.php @@ -0,0 +1,39 @@ +testClass); + $method = $reflection->getMethod('sqlEscape'); + $method->setAccessible(true); + + $result = $method->invoke($this->testClass, "line1\nline2\r\"quoted\"\\slash\0\x1a'"); + $this->assertEquals('line1\\nline2\\r\\"quoted\\"\\\\slash\\0\\Z\\\'', $result); + } + + public function testQuoteWrapsEscapedString(): void { + $reflection = new ReflectionClass($this->testClass); + $method = $reflection->getMethod('quote'); + $method->setAccessible(true); + + $result = $method->invoke($this->testClass, "O'Reilly"); + $this->assertEquals("'O\\'Reilly'", $result); + } + + protected function setUp(): void { + $this->testClass = new SqlEscapingTraitTestClass(); + } +} diff --git a/test/src/Lib/SqlEscapingTraitTestClass.php b/test/src/Lib/SqlEscapingTraitTestClass.php new file mode 100644 index 0000000..2322195 --- /dev/null +++ b/test/src/Lib/SqlEscapingTraitTestClass.php @@ -0,0 +1,18 @@ +