Skip to content

Commit

Permalink
Remove redundant zeros from SVG files (#442)
Browse files Browse the repository at this point in the history
* Add method for formatting numbers

This method takes care of stripping redundant zeros at the end of a string.

* Fix typo in method signature
  • Loading branch information
RobinvanderVliet authored Mar 3, 2024
1 parent 0efd071 commit 739fc54
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/Writer/SvgWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ public function write(QrCodeInterface $qrCode, LogoInterface $logo = null, Label

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

Expand All @@ -65,8 +65,8 @@ public function write(QrCodeInterface $qrCode, LogoInterface $logo = null, Label
for ($columnIndex = 0; $columnIndex < $matrix->getBlockCount(); ++$columnIndex) {
if (1 === $matrix->getBlockValue($rowIndex, $columnIndex)) {
$block = $xml->addChild('use');
$block->addAttribute('x', number_format($matrix->getMarginLeft() + $matrix->getBlockSize() * $columnIndex, self::DECIMAL_PRECISION, '.', ''));
$block->addAttribute('y', number_format($matrix->getMarginLeft() + $matrix->getBlockSize() * $rowIndex, self::DECIMAL_PRECISION, '.', ''));
$block->addAttribute('x', $this->formatNumber($matrix->getMarginLeft() + $matrix->getBlockSize() * $columnIndex));
$block->addAttribute('y', $this->formatNumber($matrix->getMarginLeft() + $matrix->getBlockSize() * $rowIndex));
$block->addAttribute('xlink:href', '#'.$options[self::WRITER_OPTION_BLOCK_ID], 'http://www.w3.org/1999/xlink');
}
}
Expand Down Expand Up @@ -111,4 +111,12 @@ private function addLogo(LogoInterface $logo, SvgResult $result, array $options)
$imageDefinition->addAttribute('href', $logoImageData->createDataUri());
}
}

private function formatNumber(float $number): string
{
$string = number_format($number, self::DECIMAL_PRECISION, '.', '');
$string = rtrim($string, '0');
$string = rtrim($string, '.');
return $string;
}
}

0 comments on commit 739fc54

Please sign in to comment.