Skip to content

Commit 38d4f36

Browse files
committed
New Utility::quoteArray() #9707
1 parent 1ebdb6a commit 38d4f36

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

src/Utility.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,4 +84,24 @@ public static function unique(array $array): array
8484

8585
return $result;
8686
}
87+
88+
/**
89+
* Safely quotes an array of values for an SQL statement.
90+
*
91+
* The values are quoted and then returned as a comma-separated string, so:
92+
*
93+
* ```php
94+
* Utility::quoteArray(['foo bar', 2]); // "'foo bar', '2'"
95+
* ```
96+
*/
97+
public static function quoteArray(array $value): string
98+
{
99+
$connection = _em()->getConnection();
100+
$quoted = [];
101+
foreach ($value as $v) {
102+
$quoted[] = $connection->quote($v);
103+
}
104+
105+
return implode(', ', $quoted);
106+
}
87107
}

tests/Traits/MariaDbQuotingConnection.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ class MariaDbQuotingConnection extends Connection
1717
*/
1818
public function quote(mixed $value, $type = ParameterType::STRING): string
1919
{
20+
if (in_array($value, [false, null], true)) {
21+
return '';
22+
}
23+
2024
$quoted = "'" . str_replace(["'", "\n"], ["\\'", '\\n'], (string) $value) . "'";
2125

2226
return $quoted;

tests/UtilityTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,16 @@
77
use Ecodev\Felix\Model\Model;
88
use Ecodev\Felix\Utility;
99
use EcodevTests\Felix\Blog\Model\User;
10+
use EcodevTests\Felix\Traits\TestWithEntityManager;
1011
use GraphQL\Doctrine\Definition\EntityID;
1112
use PHPUnit\Framework\TestCase;
1213
use stdClass;
1314
use Throwable;
1415

1516
final class UtilityTest extends TestCase
1617
{
18+
use TestWithEntityManager;
19+
1720
public function testGetShortClassName(): void
1821
{
1922
self::assertSame('User', Utility::getShortClassName(new User()));
@@ -123,4 +126,25 @@ public function providerNativeUniqueWillThrowWithOurTestObject(): iterable
123126
yield [SORT_STRING];
124127
yield [SORT_LOCALE_STRING];
125128
}
129+
130+
/**
131+
* @dataProvider providerQuoteArray
132+
*/
133+
public function testQuoteArray(array $input, string $expected): void
134+
{
135+
self::assertSame($expected, Utility::quoteArray($input));
136+
}
137+
138+
public function providerQuoteArray(): iterable
139+
{
140+
yield [[1, 2], "'1', '2'"];
141+
yield [['foo bar', 'baz'], "'foo bar', 'baz'"];
142+
yield [[], ''];
143+
yield [[''], "''"];
144+
yield [[false], ''];
145+
yield [[null], ''];
146+
yield [[0], "'0'"];
147+
yield [[true], "'1'"];
148+
yield [[1.23], "'1.23'"];
149+
}
126150
}

0 commit comments

Comments
 (0)