Skip to content

Commit

Permalink
Remove unallowed characters in qr code
Browse files Browse the repository at this point in the history
  • Loading branch information
sprain committed Jun 23, 2024
1 parent 7910c9c commit eb15893
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/QrCode/QrCode.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ public static function create(string $data, string $fileFormat = null): self

private function __construct(string $data, string $fileFormat)
{
$data = $this->cleanUnsupportedCharacters($data);

if (class_exists(ErrorCorrectionLevel\ErrorCorrectionLevelMedium::class)) {
// Endroid 4.x
$this->qrCode = BaseQrCode::create($data)
Expand Down Expand Up @@ -127,6 +129,13 @@ public function avoidCompactSvgs(): void
}
}

private function cleanUnsupportedCharacters(string $data): string
{
$pattern = '/([^a-zA-Z0-9.,;:\'"+\-\/()?*\[\]{}|`´~ !^#%&<>÷=@_$£àáâäçèéêëìíîïñòóôöùúûüýßÀÁÂÄÇÈÉÊËÌÍÎÏÒÓÔÖÙÚÛÜÑ\\n])/u';

return preg_replace($pattern, '', $data);
}

private function setWriterByExtension(string $extension): void
{
if (!in_array($extension, self::SUPPORTED_FILE_FORMATS)) {
Expand Down
27 changes: 27 additions & 0 deletions tests/QrCode/QrCodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,31 @@ public function stringProvider()
]
];
}

/**
* @dataProvider invalidCharactersCodeProvider
*/
public function testItRemovesInvalidCharacters(string $providedString, string $expectedString): void
{
$qrCode = QrCode::create($providedString);

$this->assertEquals(
$expectedString,
$qrCode->getText()
);
}

public function invalidCharactersCodeProvider(): array
{
return [
'keepAllAllowedCharacters' => [
'providedString' => 'a-zA-Z0-9.,;:\'+-/()?*[]{}|`´~!"#%&<>÷=@_$£^àáâäçèéêëìíîïñòóôöùúûüýßÀÁÂÄÇÈÉÊËÌÍÎÏÒÓÔÖÙÚÛÜÑ',
'expectedString' => 'a-zA-Z0-9.,;:\'+-/()?*[]{}|`´~!"#%&<>÷=@_$£^àáâäçèéêëìíîïñòóôöùúûüýßÀÁÂÄÇÈÉÊËÌÍÎÏÒÓÔÖÙÚÛÜÑ'
],
'removeUnallowedCharacters' => [
'providedString' => '«This is a test!»',
'expectedString' => 'This is a test!'
],
];
}
}

0 comments on commit eb15893

Please sign in to comment.