Skip to content

Commit 739fc54

Browse files
Remove redundant zeros from SVG files (#442)
* Add method for formatting numbers This method takes care of stripping redundant zeros at the end of a string. * Fix typo in method signature
1 parent 0efd071 commit 739fc54

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/Writer/SvgWriter.php

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,8 @@ public function write(QrCodeInterface $qrCode, LogoInterface $logo = null, Label
4848

4949
$blockDefinition = $xml->defs->addChild('rect');
5050
$blockDefinition->addAttribute('id', strval($options[self::WRITER_OPTION_BLOCK_ID]));
51-
$blockDefinition->addAttribute('width', number_format($matrix->getBlockSize(), self::DECIMAL_PRECISION, '.', ''));
52-
$blockDefinition->addAttribute('height', number_format($matrix->getBlockSize(), self::DECIMAL_PRECISION, '.', ''));
51+
$blockDefinition->addAttribute('width', $this->formatNumber($matrix->getBlockSize()));
52+
$blockDefinition->addAttribute('height', $this->formatNumber($matrix->getBlockSize()));
5353
$blockDefinition->addAttribute('fill', '#'.sprintf('%02x%02x%02x', $qrCode->getForegroundColor()->getRed(), $qrCode->getForegroundColor()->getGreen(), $qrCode->getForegroundColor()->getBlue()));
5454
$blockDefinition->addAttribute('fill-opacity', strval($qrCode->getForegroundColor()->getOpacity()));
5555

@@ -65,8 +65,8 @@ public function write(QrCodeInterface $qrCode, LogoInterface $logo = null, Label
6565
for ($columnIndex = 0; $columnIndex < $matrix->getBlockCount(); ++$columnIndex) {
6666
if (1 === $matrix->getBlockValue($rowIndex, $columnIndex)) {
6767
$block = $xml->addChild('use');
68-
$block->addAttribute('x', number_format($matrix->getMarginLeft() + $matrix->getBlockSize() * $columnIndex, self::DECIMAL_PRECISION, '.', ''));
69-
$block->addAttribute('y', number_format($matrix->getMarginLeft() + $matrix->getBlockSize() * $rowIndex, self::DECIMAL_PRECISION, '.', ''));
68+
$block->addAttribute('x', $this->formatNumber($matrix->getMarginLeft() + $matrix->getBlockSize() * $columnIndex));
69+
$block->addAttribute('y', $this->formatNumber($matrix->getMarginLeft() + $matrix->getBlockSize() * $rowIndex));
7070
$block->addAttribute('xlink:href', '#'.$options[self::WRITER_OPTION_BLOCK_ID], 'http://www.w3.org/1999/xlink');
7171
}
7272
}
@@ -111,4 +111,12 @@ private function addLogo(LogoInterface $logo, SvgResult $result, array $options)
111111
$imageDefinition->addAttribute('href', $logoImageData->createDataUri());
112112
}
113113
}
114+
115+
private function formatNumber(float $number): string
116+
{
117+
$string = number_format($number, self::DECIMAL_PRECISION, '.', '');
118+
$string = rtrim($string, '0');
119+
$string = rtrim($string, '.');
120+
return $string;
121+
}
114122
}

0 commit comments

Comments
 (0)