diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index a1ae0033..9fb3648b 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -7,7 +7,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - php-versions: ['8.4', '8.5'] + php-versions: ['8.5', '8.6'] fail-fast: false steps: - uses: actions/checkout@v5 diff --git a/composer.json b/composer.json index 66413d65..e6453673 100644 --- a/composer.json +++ b/composer.json @@ -12,7 +12,7 @@ } ], "require": { - "php": "^8.4", + "php": "^8.5", "bacon/bacon-qr-code": "^3.0" }, "require-dev": { @@ -43,7 +43,8 @@ "endroid/*": "source" }, "allow-plugins": { - "endroid/installer": true + "endroid/installer": true, + "carthage-software/mago": true } }, "extra": { diff --git a/src/Bacon/MatrixFactory.php b/src/Bacon/MatrixFactory.php index 90fe2953..48ba6d58 100644 --- a/src/Bacon/MatrixFactory.php +++ b/src/Bacon/MatrixFactory.php @@ -12,10 +12,17 @@ final readonly class MatrixFactory implements MatrixFactoryInterface { + #[\Override] public function create(QrCodeInterface $qrCode): MatrixInterface { - $baconErrorCorrectionLevel = ErrorCorrectionLevelConverter::convertToBaconErrorCorrectionLevel($qrCode->getErrorCorrectionLevel()); - $baconMatrix = Encoder::encode($qrCode->getData(), $baconErrorCorrectionLevel, strval($qrCode->getEncoding()))->getMatrix(); + $baconErrorCorrectionLevel = ErrorCorrectionLevelConverter::convertToBaconErrorCorrectionLevel( + $qrCode->getErrorCorrectionLevel(), + ); + $baconMatrix = Encoder::encode( + $qrCode->getData(), + $baconErrorCorrectionLevel, + strval($qrCode->getEncoding()), + )->getMatrix(); $blockValues = []; $columnCount = $baconMatrix->getWidth(); diff --git a/src/Builder/Builder.php b/src/Builder/Builder.php index 89c6441e..e59cbe6b 100644 --- a/src/Builder/Builder.php +++ b/src/Builder/Builder.php @@ -28,7 +28,7 @@ { public function __construct( private WriterInterface $writer = new PngWriter(), - /** @var array */ + /** @var array */ private array $writerOptions = [], private bool $validateResult = false, // QrCode options @@ -42,7 +42,7 @@ public function __construct( private ColorInterface $backgroundColor = new Color(255, 255, 255), // Label options private string $labelText = '', - private FontInterface $labelFont = new Font(__DIR__.'/../../assets/open_sans.ttf', 16), + private FontInterface $labelFont = new Font(__DIR__ . '/../../assets/open_sans.ttf', 16), private LabelAlignment $labelAlignment = LabelAlignment::Center, private MarginInterface $labelMargin = new Margin(0, 10, 10, 10), private ColorInterface $labelTextColor = new Color(0, 0, 0), @@ -51,10 +51,10 @@ public function __construct( private ?int $logoResizeToWidth = null, private ?int $logoResizeToHeight = null, private bool $logoPunchoutBackground = false, - ) { - } + ) {} - /** @param array|null $writerOptions */ + /** @param array|null $writerOptions */ + #[\Override] public function build( ?WriterInterface $writer = null, ?array $writerOptions = null, @@ -84,9 +84,9 @@ public function build( throw ValidationException::createForUnsupportedWriter(get_class($this->writer)); } - $writer = $writer ?? $this->writer; - $writerOptions = $writerOptions ?? $this->writerOptions; - $validateResult = $validateResult ?? $this->validateResult; + $writer ??= $this->writer; + $writerOptions ??= $this->writerOptions; + $validateResult ??= $this->validateResult; $createLabel = $this->labelText || $labelText; $createLogo = $this->logoPath || $logoPath; @@ -99,23 +99,27 @@ public function build( margin: $margin ?? $this->margin, roundBlockSizeMode: $roundBlockSizeMode ?? $this->roundBlockSizeMode, foregroundColor: $foregroundColor ?? $this->foregroundColor, - backgroundColor: $backgroundColor ?? $this->backgroundColor + backgroundColor: $backgroundColor ?? $this->backgroundColor, ); - $logo = $createLogo ? new Logo( - path: $logoPath ?? $this->logoPath, - resizeToWidth: $logoResizeToWidth ?? $this->logoResizeToWidth, - resizeToHeight: $logoResizeToHeight ?? $this->logoResizeToHeight, - punchoutBackground: $logoPunchoutBackground ?? $this->logoPunchoutBackground - ) : null; + $logo = $createLogo + ? new Logo( + path: $logoPath ?? $this->logoPath, + resizeToWidth: $logoResizeToWidth ?? $this->logoResizeToWidth, + resizeToHeight: $logoResizeToHeight ?? $this->logoResizeToHeight, + punchoutBackground: $logoPunchoutBackground ?? $this->logoPunchoutBackground, + ) + : null; - $label = $createLabel ? new Label( - text: $labelText ?? $this->labelText, - font: $labelFont ?? $this->labelFont, - alignment: $labelAlignment ?? $this->labelAlignment, - margin: $labelMargin ?? $this->labelMargin, - textColor: $labelTextColor ?? $this->labelTextColor - ) : null; + $label = $createLabel + ? new Label( + text: $labelText ?? $this->labelText, + font: $labelFont ?? $this->labelFont, + alignment: $labelAlignment ?? $this->labelAlignment, + margin: $labelMargin ?? $this->labelMargin, + textColor: $labelTextColor ?? $this->labelTextColor, + ) + : null; $result = $writer->write($qrCode, $logo, $label, $writerOptions); diff --git a/src/Builder/BuilderInterface.php b/src/Builder/BuilderInterface.php index 9a14dc00..ea2a8945 100644 --- a/src/Builder/BuilderInterface.php +++ b/src/Builder/BuilderInterface.php @@ -16,7 +16,7 @@ interface BuilderInterface { - /** @param array|null $writerOptions */ + /** @param array|null $writerOptions */ public function build( ?WriterInterface $writer = null, ?array $writerOptions = null, diff --git a/src/Builder/BuilderRegistry.php b/src/Builder/BuilderRegistry.php index 13b9c96f..41f8147d 100644 --- a/src/Builder/BuilderRegistry.php +++ b/src/Builder/BuilderRegistry.php @@ -9,14 +9,16 @@ final class BuilderRegistry implements BuilderRegistryInterface /** @var array */ private array $builders = []; + #[\Override] public function set(string $name, BuilderInterface $builder): void { $this->builders[$name] = $builder; } + #[\Override] public function get(string $name): BuilderInterface { - if (!isset($this->builders[$name])) { + if (null === ($this->builders[$name] ?? null)) { throw new \Exception(sprintf('Builder with name "%s" not available from registry', $name)); } diff --git a/src/Color/Color.php b/src/Color/Color.php index 5b42a4cf..4fb5d09d 100644 --- a/src/Color/Color.php +++ b/src/Color/Color.php @@ -15,39 +15,45 @@ public function __construct( private int $blue, /** @var int<0, 127> */ private int $alpha = 0, - ) { - } + ) {} + #[\Override] public function getRed(): int { return $this->red; } + #[\Override] public function getGreen(): int { return $this->green; } + #[\Override] public function getBlue(): int { return $this->blue; } + #[\Override] public function getAlpha(): int { return $this->alpha; } + #[\Override] public function getOpacity(): float { - return 1 - $this->alpha / 127; + return 1 - ($this->alpha / 127); } + #[\Override] public function getHex(): string { return sprintf('#%02x%02x%02x', $this->red, $this->green, $this->blue); } + #[\Override] public function toArray(): array { return [ diff --git a/src/Encoding/Encoding.php b/src/Encoding/Encoding.php index d6da27b5..1d87cb61 100644 --- a/src/Encoding/Encoding.php +++ b/src/Encoding/Encoding.php @@ -11,15 +11,21 @@ public function __construct( ) { if ('UTF-8' !== $value) { if (!function_exists('mb_list_encodings')) { - throw new \Exception('Unable to validate encoding: make sure the mbstring extension is installed and enabled'); + throw new \Exception( + 'Unable to validate encoding: make sure the mbstring extension is installed and enabled', + ); } - if (!in_array($value, mb_list_encodings())) { - throw new \Exception(sprintf('Invalid encoding "%s": choose one of '.implode(', ', mb_list_encodings()), $value)); + if (!in_array($value, mb_list_encodings(), strict: true)) { + throw new \Exception(sprintf( + 'Invalid encoding "%s": choose one of ' . implode(', ', mb_list_encodings()), + $value, + )); } } } + #[\Override] public function __toString(): string { return $this->value; diff --git a/src/Encoding/EncodingInterface.php b/src/Encoding/EncodingInterface.php index 17748a4b..b277d9e1 100644 --- a/src/Encoding/EncodingInterface.php +++ b/src/Encoding/EncodingInterface.php @@ -6,5 +6,6 @@ interface EncodingInterface extends \Stringable { + #[\Override] public function __toString(): string; } diff --git a/src/Exception/BlockSizeTooSmallException.php b/src/Exception/BlockSizeTooSmallException.php index f65fa85b..7049f003 100644 --- a/src/Exception/BlockSizeTooSmallException.php +++ b/src/Exception/BlockSizeTooSmallException.php @@ -4,6 +4,4 @@ namespace Endroid\QrCode\Exception; -final class BlockSizeTooSmallException extends \Exception -{ -} +final class BlockSizeTooSmallException extends \Exception {} diff --git a/src/Exception/ValidationException.php b/src/Exception/ValidationException.php index f64c4bbe..96be1dd9 100644 --- a/src/Exception/ValidationException.php +++ b/src/Exception/ValidationException.php @@ -18,6 +18,12 @@ public static function createForMissingPackage(string $packageName): self public static function createForInvalidData(string $expectedData, string $actualData): self { - return new self('The validation reader read "'.$actualData.'" instead of "'.$expectedData.'". Adjust your parameters to increase readability or disable validation.'); + return new self( + 'The validation reader read "' + . $actualData + . '" instead of "' + . $expectedData + . '". Adjust your parameters to increase readability or disable validation.', + ); } } diff --git a/src/ImageData/LabelImageData.php b/src/ImageData/LabelImageData.php index ccc89de2..a86664b1 100644 --- a/src/ImageData/LabelImageData.php +++ b/src/ImageData/LabelImageData.php @@ -11,8 +11,7 @@ private function __construct( private int $width, private int $height, - ) { - } + ) {} public static function createForLabel(LabelInterface $label): self { @@ -24,16 +23,19 @@ public static function createForLabel(LabelInterface $label): self throw new \Exception('Function "imagettfbbox" does not exist: check your FreeType installation'); } - $labelBox = imagettfbbox($label->getFont()->getSize(), 0, $label->getFont()->getPath(), $label->getText()); + /** @var array{int, int, int, int, int, int, int, int}|false $labelBox FreeType returns four coordinate pairs. */ + $labelBox = imagettfbbox( + $label->getFont()->getSize(), + angle: 0, + font_filename: $label->getFont()->getPath(), + string: $label->getText(), + ); if (!is_array($labelBox)) { throw new \Exception('Unable to generate label image box: check your FreeType installation'); } - return new self( - intval($labelBox[2] - $labelBox[0]), - intval($labelBox[0] - $labelBox[7]) - ); + return new self(intval($labelBox[2] - $labelBox[0]), intval($labelBox[0] - $labelBox[7])); } public function getWidth(): int diff --git a/src/ImageData/LogoImageData.php b/src/ImageData/LogoImageData.php index d4fd610e..9997d87f 100644 --- a/src/ImageData/LogoImageData.php +++ b/src/ImageData/LogoImageData.php @@ -15,8 +15,7 @@ private function __construct( private int $width, private int $height, private bool $punchoutBackground, - ) { - } + ) {} public static function createForLogo(LogoInterface $logo): self { @@ -25,14 +24,16 @@ public static function createForLogo(LogoInterface $logo): self if (!is_string($data)) { $errorDetails = error_get_last()['message'] ?? 'invalid data'; - throw new \Exception(sprintf('Could not read logo image data from path "%s": %s', $logo->getPath(), $errorDetails)); + throw new \Exception(sprintf( + 'Could not read logo image data from path "%s": %s', + $logo->getPath(), + $errorDetails, + )); } - if (false !== filter_var($logo->getPath(), FILTER_VALIDATE_URL)) { - $mimeType = self::detectMimeTypeFromUrl($logo->getPath()); - } else { - $mimeType = self::detectMimeTypeFromPath($logo->getPath()); - } + $mimeType = false !== filter_var($logo->getPath(), FILTER_VALIDATE_URL) + ? self::detectMimeTypeFromUrl($logo->getPath()) + : self::detectMimeTypeFromPath($logo->getPath()); $width = $logo->getResizeToWidth(); $height = $logo->getResizeToHeight(); @@ -54,7 +55,11 @@ public static function createForLogo(LogoInterface $logo): self if (!$image) { $errorDetails = error_get_last()['message'] ?? 'invalid data'; - throw new \Exception(sprintf('Unable to parse image data at path "%s": %s', $logo->getPath(), $errorDetails)); + throw new \Exception(sprintf( + 'Unable to parse image data at path "%s": %s', + $logo->getPath(), + $errorDetails, + )); } // No target width and height specified: use from original image @@ -64,12 +69,26 @@ public static function createForLogo(LogoInterface $logo): self // Only target width specified: calculate height if (null !== $width) { - return new self($data, $image, $mimeType, $width, intval(imagesy($image) * $width / imagesx($image)), $logo->getPunchoutBackground()); + return new self( + $data, + $image, + $mimeType, + $width, + intval((imagesy($image) * $width) / imagesx($image)), + $logo->getPunchoutBackground(), + ); } // Only target height specified: calculate width if (null !== $height) { - return new self($data, $image, $mimeType, intval(imagesx($image) * $height / imagesy($image)), $height, $logo->getPunchoutBackground()); + return new self( + $data, + $image, + $mimeType, + intval((imagesx($image) * $height) / imagesy($image)), + $height, + $logo->getPunchoutBackground(), + ); } return new self($data, $image, $mimeType, imagesx($image), imagesy($image), $logo->getPunchoutBackground()); @@ -111,24 +130,35 @@ public function getPunchoutBackground(): bool public function createDataUri(): string { - return 'data:'.$this->mimeType.';base64,'.base64_encode($this->data); + return 'data:' . $this->mimeType . ';base64,' . base64_encode($this->data); } private static function detectMimeTypeFromUrl(string $url): string { - $headers = get_headers($url, true); + /** @var array>|false $headers */ + $headers = get_headers($url, associative: true); if (!is_array($headers)) { - throw new \Exception(sprintf('Could not retrieve headers to determine content type for logo URL "%s"', $url)); + throw new \Exception(sprintf( + 'Could not retrieve headers to determine content type for logo URL "%s"', + $url, + )); } - $headers = array_combine(array_map('strtolower', array_keys($headers)), $headers); + $headers = array_combine(array_map(static fn(string|int $key): string => strtolower(strval( + $key, + )), array_keys($headers)), $headers); - if (!isset($headers['content-type'])) { + if (null === ($headers['content-type'] ?? null)) { throw new \Exception(sprintf('Content type could not be determined for logo URL "%s"', $url)); } - return is_array($headers['content-type']) ? $headers['content-type'][1] : $headers['content-type']; + return is_array($headers['content-type']) + ? $headers['content-type'][1] ?? throw new \TypeError(sprintf( + 'Content type could not be determined for logo URL "%s"', + $url, + )) + : $headers['content-type']; } private static function detectMimeTypeFromPath(string $path): string diff --git a/src/Label/Font/Font.php b/src/Label/Font/Font.php index e796c556..3ba74361 100644 --- a/src/Label/Font/Font.php +++ b/src/Label/Font/Font.php @@ -20,11 +20,13 @@ private function assertValidPath(string $path): void } } + #[\Override] public function getPath(): string { return $this->path; } + #[\Override] public function getSize(): int { return $this->size; diff --git a/src/Label/Font/OpenSans.php b/src/Label/Font/OpenSans.php index 330dc5b6..a92dd667 100644 --- a/src/Label/Font/OpenSans.php +++ b/src/Label/Font/OpenSans.php @@ -8,14 +8,15 @@ { public function __construct( private int $size = 16, - ) { - } + ) {} + #[\Override] public function getPath(): string { - return __DIR__.'/../../../assets/open_sans.ttf'; + return __DIR__ . '/../../../assets/open_sans.ttf'; } + #[\Override] public function getSize(): int { return $this->size; diff --git a/src/Label/Label.php b/src/Label/Label.php index d7a7abaa..bc38a0c5 100644 --- a/src/Label/Label.php +++ b/src/Label/Label.php @@ -15,33 +15,37 @@ { public function __construct( private string $text, - private FontInterface $font = new Font(__DIR__.'/../../assets/open_sans.ttf', 16), + private FontInterface $font = new Font(__DIR__ . '/../../assets/open_sans.ttf', 16), private LabelAlignment $alignment = LabelAlignment::Center, private MarginInterface $margin = new Margin(0, 10, 10, 10), private ColorInterface $textColor = new Color(0, 0, 0), - ) { - } + ) {} + #[\Override] public function getText(): string { return $this->text; } + #[\Override] public function getFont(): FontInterface { return $this->font; } + #[\Override] public function getAlignment(): LabelAlignment { return $this->alignment; } + #[\Override] public function getMargin(): MarginInterface { return $this->margin; } + #[\Override] public function getTextColor(): ColorInterface { return $this->textColor; diff --git a/src/Label/Margin/Margin.php b/src/Label/Margin/Margin.php index fd11f5cc..a1d4aab3 100644 --- a/src/Label/Margin/Margin.php +++ b/src/Label/Margin/Margin.php @@ -11,30 +11,34 @@ public function __construct( private int $right, private int $bottom, private int $left, - ) { - } + ) {} + #[\Override] public function getTop(): int { return $this->top; } + #[\Override] public function getRight(): int { return $this->right; } + #[\Override] public function getBottom(): int { return $this->bottom; } + #[\Override] public function getLeft(): int { return $this->left; } /** @return array */ + #[\Override] public function toArray(): array { return [ diff --git a/src/Logo/Logo.php b/src/Logo/Logo.php index bc4691fd..cd1a0655 100644 --- a/src/Logo/Logo.php +++ b/src/Logo/Logo.php @@ -11,24 +11,27 @@ public function __construct( private ?int $resizeToWidth = null, private ?int $resizeToHeight = null, private bool $punchoutBackground = false, - ) { - } + ) {} + #[\Override] public function getPath(): string { return $this->path; } + #[\Override] public function getResizeToWidth(): ?int { return $this->resizeToWidth; } + #[\Override] public function getResizeToHeight(): ?int { return $this->resizeToHeight; } + #[\Override] public function getPunchoutBackground(): bool { return $this->punchoutBackground; diff --git a/src/Matrix/Matrix.php b/src/Matrix/Matrix.php index 5a474ed3..83659238 100644 --- a/src/Matrix/Matrix.php +++ b/src/Matrix/Matrix.php @@ -24,18 +24,18 @@ public function __construct( ) { $blockSize = $size / $this->getBlockCount(); $innerSize = $size; - $outerSize = $size + 2 * $margin; + $outerSize = $size + (2 * $margin); switch ($roundBlockSizeMode) { case RoundBlockSizeMode::Enlarge: $blockSize = intval(ceil($blockSize)); $innerSize = intval($blockSize * $this->getBlockCount()); - $outerSize = $innerSize + 2 * $margin; + $outerSize = $innerSize + (2 * $margin); break; case RoundBlockSizeMode::Shrink: $blockSize = intval(floor($blockSize)); $innerSize = intval($blockSize * $this->getBlockCount()); - $outerSize = $innerSize + 2 * $margin; + $outerSize = $innerSize + (2 * $margin); break; case RoundBlockSizeMode::Margin: $blockSize = intval(floor($blockSize)); @@ -44,7 +44,9 @@ public function __construct( } if ($blockSize < 1) { - throw new BlockSizeTooSmallException('Too much data: increase image dimensions or lower error correction level'); + throw new BlockSizeTooSmallException( + 'Too much data: increase image dimensions or lower error correction level', + ); } $this->blockSize = $blockSize; @@ -54,36 +56,47 @@ public function __construct( $this->marginRight = $this->outerSize - $this->innerSize - $this->marginLeft; } + /** @return int<0, 1> */ + #[\Override] public function getBlockValue(int $rowIndex, int $columnIndex): int { - return $this->blockValues[$rowIndex][$columnIndex]; + return ( + $this->blockValues[$rowIndex][$columnIndex] ?? throw new \TypeError('Matrix coordinates are out of bounds') + ); } + /** @return non-negative-int */ + #[\Override] public function getBlockCount(): int { - return count($this->blockValues[0]); + return count($this->blockValues[0] ?? throw new \TypeError('Matrix has no first row')); } + #[\Override] public function getBlockSize(): float { return $this->blockSize; } + #[\Override] public function getInnerSize(): int { return $this->innerSize; } + #[\Override] public function getOuterSize(): int { return $this->outerSize; } + #[\Override] public function getMarginLeft(): int { return $this->marginLeft; } + #[\Override] public function getMarginRight(): int { return $this->marginRight; diff --git a/src/Matrix/MatrixInterface.php b/src/Matrix/MatrixInterface.php index f8d1e166..22e12108 100644 --- a/src/Matrix/MatrixInterface.php +++ b/src/Matrix/MatrixInterface.php @@ -6,8 +6,10 @@ interface MatrixInterface { + /** @return int<0, 1> */ public function getBlockValue(int $rowIndex, int $columnIndex): int; + /** @return non-negative-int */ public function getBlockCount(): int; public function getBlockSize(): float; diff --git a/src/QrCode.php b/src/QrCode.php index df828646..6640a592 100644 --- a/src/QrCode.php +++ b/src/QrCode.php @@ -20,44 +20,51 @@ public function __construct( private RoundBlockSizeMode $roundBlockSizeMode = RoundBlockSizeMode::Margin, private ColorInterface $foregroundColor = new Color(0, 0, 0), private ColorInterface $backgroundColor = new Color(255, 255, 255), - ) { - } + ) {} + #[\Override] public function getData(): string { return $this->data; } + #[\Override] public function getEncoding(): EncodingInterface { return $this->encoding; } + #[\Override] public function getErrorCorrectionLevel(): ErrorCorrectionLevel { return $this->errorCorrectionLevel; } + #[\Override] public function getSize(): int { return $this->size; } + #[\Override] public function getMargin(): int { return $this->margin; } + #[\Override] public function getRoundBlockSizeMode(): RoundBlockSizeMode { return $this->roundBlockSizeMode; } + #[\Override] public function getForegroundColor(): ColorInterface { return $this->foregroundColor; } + #[\Override] public function getBackgroundColor(): ColorInterface { return $this->backgroundColor; diff --git a/src/Writer/BinaryWriter.php b/src/Writer/BinaryWriter.php index 8e0c7e8c..654a4ecc 100644 --- a/src/Writer/BinaryWriter.php +++ b/src/Writer/BinaryWriter.php @@ -13,8 +13,13 @@ final readonly class BinaryWriter implements WriterInterface { - public function write(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?LabelInterface $label = null, array $options = []): ResultInterface - { + #[\Override] + public function write( + QrCodeInterface $qrCode, + ?LogoInterface $logo = null, + ?LabelInterface $label = null, + array $options = [], + ): ResultInterface { $matrixFactory = new MatrixFactory(); $matrix = $matrixFactory->create($qrCode); diff --git a/src/Writer/ConsoleWriter.php b/src/Writer/ConsoleWriter.php index e3bb7c31..f52aef22 100644 --- a/src/Writer/ConsoleWriter.php +++ b/src/Writer/ConsoleWriter.php @@ -13,8 +13,13 @@ final readonly class ConsoleWriter implements WriterInterface { - public function write(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?LabelInterface $label = null, $options = []): ResultInterface - { + #[\Override] + public function write( + QrCodeInterface $qrCode, + ?LogoInterface $logo = null, + ?LabelInterface $label = null, + $options = [], + ): ResultInterface { $matrixFactory = new MatrixFactory(); $matrix = $matrixFactory->create($qrCode); diff --git a/src/Writer/DebugWriter.php b/src/Writer/DebugWriter.php index 8910a809..c1226fb2 100644 --- a/src/Writer/DebugWriter.php +++ b/src/Writer/DebugWriter.php @@ -13,14 +13,20 @@ final readonly class DebugWriter implements WriterInterface, ValidatingWriterInterface { - public function write(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?LabelInterface $label = null, array $options = []): ResultInterface - { + #[\Override] + public function write( + QrCodeInterface $qrCode, + ?LogoInterface $logo = null, + ?LabelInterface $label = null, + array $options = [], + ): ResultInterface { $matrixFactory = new MatrixFactory(); $matrix = $matrixFactory->create($qrCode); return new DebugResult($matrix, $qrCode, $logo, $label, $options); } + #[\Override] public function validateResult(ResultInterface $result, string $expectedData): void { if (!$result instanceof DebugResult) { diff --git a/src/Writer/EpsWriter.php b/src/Writer/EpsWriter.php index 2f419675..37f6f49e 100644 --- a/src/Writer/EpsWriter.php +++ b/src/Writer/EpsWriter.php @@ -5,6 +5,7 @@ namespace Endroid\QrCode\Writer; use Endroid\QrCode\Bacon\MatrixFactory; +use Endroid\QrCode\Color\ColorInterface; use Endroid\QrCode\Label\LabelInterface; use Endroid\QrCode\Logo\LogoInterface; use Endroid\QrCode\QrCodeInterface; @@ -13,32 +14,68 @@ final readonly class EpsWriter implements WriterInterface { - public const DECIMAL_PRECISION = 10; + public const int DECIMAL_PRECISION = 10; - public function write(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?LabelInterface $label = null, array $options = []): ResultInterface - { + #[\Override] + public function write( + QrCodeInterface $qrCode, + ?LogoInterface $logo = null, + ?LabelInterface $label = null, + array $options = [], + ): ResultInterface { $matrixFactory = new MatrixFactory(); $matrix = $matrixFactory->create($qrCode); $lines = [ '%!PS-Adobe-3.0 EPSF-3.0', - '%%BoundingBox: 0 0 '.$matrix->getOuterSize().' '.$matrix->getOuterSize(), + '%%BoundingBox: 0 0 ' . $matrix->getOuterSize() . ' ' . $matrix->getOuterSize(), '/F { rectfill } def', - number_format($qrCode->getBackgroundColor()->getRed() / 100, 2, '.', ',').' '.number_format($qrCode->getBackgroundColor()->getGreen() / 100, 2, '.', ',').' '.number_format($qrCode->getBackgroundColor()->getBlue() / 100, 2, '.', ',').' setrgbcolor', - '0 0 '.$matrix->getOuterSize().' '.$matrix->getOuterSize().' F', - number_format($qrCode->getForegroundColor()->getRed() / 100, 2, '.', ',').' '.number_format($qrCode->getForegroundColor()->getGreen() / 100, 2, '.', ',').' '.number_format($qrCode->getForegroundColor()->getBlue() / 100, 2, '.', ',').' setrgbcolor', + $this->formatColor($qrCode->getBackgroundColor()) . ' setrgbcolor', + '0 0 ' . $matrix->getOuterSize() . ' ' . $matrix->getOuterSize() . ' F', + $this->formatColor($qrCode->getForegroundColor()) . ' setrgbcolor', ]; for ($rowIndex = 0; $rowIndex < $matrix->getBlockCount(); ++$rowIndex) { for ($columnIndex = 0; $columnIndex < $matrix->getBlockCount(); ++$columnIndex) { - if (1 === $matrix->getBlockValue($matrix->getBlockCount() - 1 - $rowIndex, $columnIndex)) { - $x = $matrix->getMarginLeft() + $matrix->getBlockSize() * $columnIndex; - $y = $matrix->getMarginLeft() + $matrix->getBlockSize() * $rowIndex; - $lines[] = number_format($x, self::DECIMAL_PRECISION, '.', '').' '.number_format($y, self::DECIMAL_PRECISION, '.', '').' '.number_format($matrix->getBlockSize(), self::DECIMAL_PRECISION, '.', '').' '.number_format($matrix->getBlockSize(), self::DECIMAL_PRECISION, '.', '').' F'; + if (1 !== $matrix->getBlockValue($matrix->getBlockCount() - 1 - $rowIndex, $columnIndex)) { + continue; } + + $x = $matrix->getMarginLeft() + ($matrix->getBlockSize() * $columnIndex); + $y = $matrix->getMarginLeft() + ($matrix->getBlockSize() * $rowIndex); + $lines[] = + number_format($x, self::DECIMAL_PRECISION, decimal_separator: '.', thousands_separator: '') + . ' ' + . number_format($y, self::DECIMAL_PRECISION, decimal_separator: '.', thousands_separator: '') + . ' ' + . number_format( + $matrix->getBlockSize(), + self::DECIMAL_PRECISION, + decimal_separator: '.', + thousands_separator: '', + ) + . ' ' + . number_format( + $matrix->getBlockSize(), + self::DECIMAL_PRECISION, + decimal_separator: '.', + thousands_separator: '', + ) + . ' F'; } } return new EpsResult($matrix, $lines); } + + private function formatColor(ColorInterface $color): string + { + return ( + number_format($color->getRed() / 100, decimals: 2, decimal_separator: '.', thousands_separator: ',') + . ' ' + . number_format($color->getGreen() / 100, decimals: 2, decimal_separator: '.', thousands_separator: ',') + . ' ' + . number_format($color->getBlue() / 100, decimals: 2, decimal_separator: '.', thousands_separator: ',') + ); + } } diff --git a/src/Writer/GdTrait.php b/src/Writer/GdTrait.php index a3069d64..f0a7955b 100644 --- a/src/Writer/GdTrait.php +++ b/src/Writer/GdTrait.php @@ -28,57 +28,23 @@ public function getMatrix(QrCodeInterface $qrCode): MatrixInterface } /** @param array $options */ - public function writeGd(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?LabelInterface $label = null, array $options = []): GdResult - { + public function writeGd( + QrCodeInterface $qrCode, + ?LogoInterface $logo = null, + ?LabelInterface $label = null, + array $options = [], + ): GdResult { + // Options are reserved for format-specific writers; GD rendering is shared. + unset($options); + if (!extension_loaded('gd')) { - throw new \Exception('Unable to generate image: please check if the GD extension is enabled and configured correctly'); + throw new \Exception( + 'Unable to generate image: please check if the GD extension is enabled and configured correctly', + ); } $matrix = $this->getMatrix($qrCode); - - $baseBlockSize = RoundBlockSizeMode::None === $qrCode->getRoundBlockSizeMode() ? 10 : intval($matrix->getBlockSize()); - /** @var int<1, max> $baseImageSize */ - $baseImageSize = $matrix->getBlockCount() * $baseBlockSize; - $baseImage = imagecreatetruecolor($baseImageSize, $baseImageSize); - - if (!$baseImage) { - throw new \Exception('Unable to generate image: please check if the GD extension is enabled and configured correctly'); - } - - $foregroundColor = imagecolorallocatealpha( - $baseImage, - $qrCode->getForegroundColor()->getRed(), - $qrCode->getForegroundColor()->getGreen(), - $qrCode->getForegroundColor()->getBlue(), - $qrCode->getForegroundColor()->getAlpha() - ); - - if (false === $foregroundColor) { - throw new \Exception('Unable to generate image: please check if the GD extension is enabled and configured correctly'); - } - - $transparentColor = imagecolorallocatealpha($baseImage, 255, 255, 255, 127); - - if (false === $transparentColor) { - throw new \Exception('Unable to generate image: please check if the GD extension is enabled and configured correctly'); - } - - imagefill($baseImage, 0, 0, $transparentColor); - - for ($rowIndex = 0; $rowIndex < $matrix->getBlockCount(); ++$rowIndex) { - for ($columnIndex = 0; $columnIndex < $matrix->getBlockCount(); ++$columnIndex) { - if (1 === $matrix->getBlockValue($rowIndex, $columnIndex)) { - imagefilledrectangle( - $baseImage, - $columnIndex * $baseBlockSize, - $rowIndex * $baseBlockSize, - ($columnIndex + 1) * $baseBlockSize - 1, - ($rowIndex + 1) * $baseBlockSize - 1, - $foregroundColor - ); - } - } - } + $baseImage = $this->createBaseImage($qrCode, $matrix); /** @var int<1, max> $targetWidth */ $targetWidth = $matrix->getOuterSize(); @@ -87,14 +53,17 @@ public function writeGd(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?L if ($label instanceof LabelInterface) { $labelImageData = LabelImageData::createForLabel($label); - $targetHeight += $labelImageData->getHeight() + $label->getMargin()->getTop() + $label->getMargin()->getBottom(); + $targetHeight += + $labelImageData->getHeight() + $label->getMargin()->getTop() + $label->getMargin()->getBottom(); } /** @var int<1, max> $targetHeight */ $targetImage = imagecreatetruecolor($targetWidth, $targetHeight); if (!$targetImage) { - throw new \Exception('Unable to generate image: please check if the GD extension is enabled and configured correctly'); + throw new \Exception( + 'Unable to generate image: please check if the GD extension is enabled and configured correctly', + ); } $backgroundColor = imagecolorallocatealpha( @@ -102,30 +71,32 @@ public function writeGd(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?L $qrCode->getBackgroundColor()->getRed(), $qrCode->getBackgroundColor()->getGreen(), $qrCode->getBackgroundColor()->getBlue(), - $qrCode->getBackgroundColor()->getAlpha() + $qrCode->getBackgroundColor()->getAlpha(), ); if (false === $backgroundColor) { - throw new \Exception('Unable to generate image: please check if the GD extension is enabled and configured correctly'); + throw new \Exception( + 'Unable to generate image: please check if the GD extension is enabled and configured correctly', + ); } - imagefill($targetImage, 0, 0, $backgroundColor); + imagefill($targetImage, x: 0, y: 0, color: $backgroundColor); imagecopyresampled( $targetImage, $baseImage, $matrix->getMarginLeft(), $matrix->getMarginLeft(), - 0, - 0, - $matrix->getInnerSize(), - $matrix->getInnerSize(), - imagesx($baseImage), - imagesy($baseImage) + src_x: 0, + src_y: 0, + dst_width: $matrix->getInnerSize(), + dst_height: $matrix->getInnerSize(), + src_width: imagesx($baseImage), + src_height: imagesy($baseImage), ); if ($qrCode->getBackgroundColor()->getAlpha() > 0) { - imagesavealpha($targetImage, true); + imagesavealpha($targetImage, enable: true); } $result = new GdResult($matrix, $targetImage); @@ -141,6 +112,65 @@ public function writeGd(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?L return $result; } + private function createBaseImage(QrCodeInterface $qrCode, MatrixInterface $matrix): \GdImage + { + $baseBlockSize = RoundBlockSizeMode::None === $qrCode->getRoundBlockSizeMode() + ? 10 + : intval($matrix->getBlockSize()); + /** @var int<1, max> $baseImageSize */ + $baseImageSize = $matrix->getBlockCount() * $baseBlockSize; + $baseImage = imagecreatetruecolor($baseImageSize, $baseImageSize); + + if (!$baseImage) { + throw new \Exception( + 'Unable to generate image: please check if the GD extension is enabled and configured correctly', + ); + } + + $foregroundColor = imagecolorallocatealpha( + $baseImage, + $qrCode->getForegroundColor()->getRed(), + $qrCode->getForegroundColor()->getGreen(), + $qrCode->getForegroundColor()->getBlue(), + $qrCode->getForegroundColor()->getAlpha(), + ); + + if (false === $foregroundColor) { + throw new \Exception( + 'Unable to generate image: please check if the GD extension is enabled and configured correctly', + ); + } + + $transparentColor = imagecolorallocatealpha($baseImage, red: 255, green: 255, blue: 255, alpha: 127); + + if (false === $transparentColor) { + throw new \Exception( + 'Unable to generate image: please check if the GD extension is enabled and configured correctly', + ); + } + + imagefill($baseImage, x: 0, y: 0, color: $transparentColor); + + for ($rowIndex = 0; $rowIndex < $matrix->getBlockCount(); ++$rowIndex) { + for ($columnIndex = 0; $columnIndex < $matrix->getBlockCount(); ++$columnIndex) { + if (1 !== $matrix->getBlockValue($rowIndex, $columnIndex)) { + continue; + } + + imagefilledrectangle( + $baseImage, + $columnIndex * $baseBlockSize, + $rowIndex * $baseBlockSize, + (($columnIndex + 1) * $baseBlockSize) - 1, + (($rowIndex + 1) * $baseBlockSize) - 1, + $foregroundColor, + ); + } + } + + return $baseImage; + } + private function addLogo(LogoInterface $logo, GdResult $result): GdResult { $logoImageData = LogoImageData::createForLogo($logo); @@ -153,17 +183,19 @@ private function addLogo(LogoInterface $logo, GdResult $result): GdResult $matrix = $result->getMatrix(); if ($logoImageData->getPunchoutBackground()) { - $transparent = imagecolorallocatealpha($targetImage, 255, 255, 255, 127); + $transparent = imagecolorallocatealpha($targetImage, red: 255, green: 255, blue: 255, alpha: 127); if (false === $transparent) { - throw new \Exception('Unable to allocate color: please check if the GD extension is enabled and configured correctly'); + throw new \Exception( + 'Unable to allocate color: please check if the GD extension is enabled and configured correctly', + ); } - imagealphablending($targetImage, false); - $xOffsetStart = intval($matrix->getOuterSize() / 2 - $logoImageData->getWidth() / 2); - $yOffsetStart = intval($matrix->getOuterSize() / 2 - $logoImageData->getHeight() / 2); - for ($xOffset = $xOffsetStart; $xOffset < $xOffsetStart + $logoImageData->getWidth(); ++$xOffset) { - for ($yOffset = $yOffsetStart; $yOffset < $yOffsetStart + $logoImageData->getHeight(); ++$yOffset) { + imagealphablending($targetImage, enable: false); + $xOffsetStart = intval(($matrix->getOuterSize() / 2) - ($logoImageData->getWidth() / 2)); + $yOffsetStart = intval(($matrix->getOuterSize() / 2) - ($logoImageData->getHeight() / 2)); + for ($xOffset = $xOffsetStart; $xOffset < ($xOffsetStart + $logoImageData->getWidth()); ++$xOffset) { + for ($yOffset = $yOffsetStart; $yOffset < ($yOffsetStart + $logoImageData->getHeight()); ++$yOffset) { imagesetpixel($targetImage, $xOffset, $yOffset, $transparent); } } @@ -172,14 +204,14 @@ private function addLogo(LogoInterface $logo, GdResult $result): GdResult imagecopyresampled( $targetImage, $logoImageData->getImage(), - intval($matrix->getOuterSize() / 2 - $logoImageData->getWidth() / 2), - intval($matrix->getOuterSize() / 2 - $logoImageData->getHeight() / 2), - 0, - 0, - $logoImageData->getWidth(), - $logoImageData->getHeight(), - imagesx($logoImageData->getImage()), - imagesy($logoImageData->getImage()) + intval(($matrix->getOuterSize() / 2) - ($logoImageData->getWidth() / 2)), + intval(($matrix->getOuterSize() / 2) - ($logoImageData->getHeight() / 2)), + src_x: 0, + src_y: 0, + dst_width: $logoImageData->getWidth(), + dst_height: $logoImageData->getHeight(), + src_width: imagesx($logoImageData->getImage()), + src_height: imagesy($logoImageData->getImage()), ); return new GdResult($matrix, $targetImage); @@ -196,23 +228,33 @@ private function addLabel(LabelInterface $label, GdResult $result): GdResult $label->getTextColor()->getRed(), $label->getTextColor()->getGreen(), $label->getTextColor()->getBlue(), - $label->getTextColor()->getAlpha() + $label->getTextColor()->getAlpha(), ); if (false === $textColor) { - throw new \Exception('Unable to allocate color: please check if the GD extension is enabled and configured correctly'); + throw new \Exception( + 'Unable to allocate color: please check if the GD extension is enabled and configured correctly', + ); } - $x = intval(imagesx($targetImage) / 2 - $labelImageData->getWidth() / 2); + $x = match ($label->getAlignment()) { + LabelAlignment::Left => $label->getMargin()->getLeft(), + LabelAlignment::Right => imagesx($targetImage) - $labelImageData->getWidth() + - $label->getMargin()->getRight(), + default => intval((imagesx($targetImage) / 2) - ($labelImageData->getWidth() / 2)), + }; $y = imagesy($targetImage) - $label->getMargin()->getBottom(); - if (LabelAlignment::Left === $label->getAlignment()) { - $x = $label->getMargin()->getLeft(); - } elseif (LabelAlignment::Right === $label->getAlignment()) { - $x = imagesx($targetImage) - $labelImageData->getWidth() - $label->getMargin()->getRight(); - } - - imagettftext($targetImage, $label->getFont()->getSize(), 0, $x, $y, $textColor, $label->getFont()->getPath(), $label->getText()); + imagettftext( + $targetImage, + $label->getFont()->getSize(), + angle: 0, + x: $x, + y: $y, + color: $textColor, + font_filename: $label->getFont()->getPath(), + text: $label->getText(), + ); return new GdResult($result->getMatrix(), $targetImage); } diff --git a/src/Writer/GifWriter.php b/src/Writer/GifWriter.php index 52cc441c..fc9d0735 100644 --- a/src/Writer/GifWriter.php +++ b/src/Writer/GifWriter.php @@ -14,8 +14,13 @@ { use GdTrait; - public function write(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?LabelInterface $label = null, array $options = []): ResultInterface - { + #[\Override] + public function write( + QrCodeInterface $qrCode, + ?LogoInterface $logo = null, + ?LabelInterface $label = null, + array $options = [], + ): ResultInterface { $gdResult = $this->writeGd($qrCode, $logo, $label, $options); return new GifResult($gdResult->getMatrix(), $gdResult->getImage()); diff --git a/src/Writer/PdfWriter.php b/src/Writer/PdfWriter.php index 3f0cd734..a580ab63 100644 --- a/src/Writer/PdfWriter.php +++ b/src/Writer/PdfWriter.php @@ -7,30 +7,34 @@ use Endroid\QrCode\Bacon\MatrixFactory; use Endroid\QrCode\Label\LabelInterface; use Endroid\QrCode\Logo\LogoInterface; +use Endroid\QrCode\Matrix\MatrixInterface; use Endroid\QrCode\QrCodeInterface; use Endroid\QrCode\Writer\Result\PdfResult; use Endroid\QrCode\Writer\Result\ResultInterface; final readonly class PdfWriter implements WriterInterface { - public const WRITER_OPTION_UNIT = 'unit'; - public const WRITER_OPTION_PDF = 'fpdf'; - public const WRITER_OPTION_X = 'x'; - public const WRITER_OPTION_Y = 'y'; - public const WRITER_OPTION_LINK = 'link'; - - public function write(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?LabelInterface $label = null, array $options = []): ResultInterface - { + public const string WRITER_OPTION_UNIT = 'unit'; + public const string WRITER_OPTION_PDF = 'fpdf'; + public const string WRITER_OPTION_X = 'x'; + public const string WRITER_OPTION_Y = 'y'; + public const string WRITER_OPTION_LINK = 'link'; + + #[\Override] + public function write( + QrCodeInterface $qrCode, + ?LogoInterface $logo = null, + ?LabelInterface $label = null, + array $options = [], + ): ResultInterface { + /** @var array{unit?: string|null, fpdf?: mixed, x?: int|float|null, y?: int|float|null, link?: string|int|null} $options */ $matrixFactory = new MatrixFactory(); $matrix = $matrixFactory->create($qrCode); - $unit = 'mm'; - if (isset($options[self::WRITER_OPTION_UNIT])) { - $unit = $options[self::WRITER_OPTION_UNIT]; - } + $unit = $options[self::WRITER_OPTION_UNIT] ?? 'mm'; $allowedUnits = ['mm', 'pt', 'cm', 'in']; - if (!in_array($unit, $allowedUnits)) { + if (!in_array($unit, $allowedUnits, strict: true)) { throw new \Exception(sprintf('PDF Measure unit should be one of [%s]', implode(', ', $allowedUnits))); } @@ -52,62 +56,86 @@ public function write(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?Lab throw new \Exception('PDF Writer does not support alpha channels'); } - if (isset($options[self::WRITER_OPTION_PDF])) { - $fpdf = $options[self::WRITER_OPTION_PDF]; - if (!$fpdf instanceof \FPDF) { - throw new \Exception('pdf option must be an instance of FPDF'); - } - } else { - // @todo Check how to add label height later - $fpdf = new \FPDF('P', $unit, [$matrix->getOuterSize(), $matrix->getOuterSize() + $labelSpace]); - $fpdf->AddPage(); - } - - $x = 0; - if (isset($options[self::WRITER_OPTION_X])) { - $x = $options[self::WRITER_OPTION_X]; - } - $y = 0; - if (isset($options[self::WRITER_OPTION_Y])) { - $y = $options[self::WRITER_OPTION_Y]; - } + $fpdf = $this->createPdf($options[self::WRITER_OPTION_PDF] ?? null, $unit, $matrix, $labelSpace); + $x = $options[self::WRITER_OPTION_X] ?? 0; + $y = $options[self::WRITER_OPTION_Y] ?? 0; $fpdf->SetFillColor($backgroundColor->getRed(), $backgroundColor->getGreen(), $backgroundColor->getBlue()); $fpdf->Rect($x, $y, $matrix->getOuterSize(), $matrix->getOuterSize(), 'F'); $fpdf->SetFillColor($foregroundColor->getRed(), $foregroundColor->getGreen(), $foregroundColor->getBlue()); - for ($rowIndex = 0; $rowIndex < $matrix->getBlockCount(); ++$rowIndex) { - for ($columnIndex = 0; $columnIndex < $matrix->getBlockCount(); ++$columnIndex) { - if (1 === $matrix->getBlockValue($rowIndex, $columnIndex)) { - $fpdf->Rect( - $x + $matrix->getMarginLeft() + ($columnIndex * $matrix->getBlockSize()), - $y + $matrix->getMarginLeft() + ($rowIndex * $matrix->getBlockSize()), - $matrix->getBlockSize(), - $matrix->getBlockSize(), - 'F' - ); - } - } - } + $this->drawMatrix($fpdf, $matrix, $x, $y); if ($logo instanceof LogoInterface) { $this->addLogo($logo, $fpdf, $x, $y, $matrix->getOuterSize()); } if ($label instanceof LabelInterface) { - $fpdf->SetXY($x, $y + $matrix->getOuterSize() + $labelSpace - 25); - $fpdf->SetFont('Helvetica', '', $label->getFont()->getSize()); - $fpdf->Cell($matrix->getOuterSize(), 0, $label->getText(), 0, 0, 'C'); + $this->addLabel( + $label, + $fpdf, + $x, + $y + $matrix->getOuterSize() + $labelSpace - 25, + $matrix->getOuterSize(), + ); } - if (isset($options[self::WRITER_OPTION_LINK])) { - $link = $options[self::WRITER_OPTION_LINK]; - $fpdf->Link($x, $y, $x + $matrix->getOuterSize(), $y + $matrix->getOuterSize(), $link); + if (null !== ($options[self::WRITER_OPTION_LINK] ?? null)) { + $fpdf->Link( + $x, + $y, + $x + $matrix->getOuterSize(), + $y + $matrix->getOuterSize(), + $options[self::WRITER_OPTION_LINK], + ); } return new PdfResult($matrix, $fpdf); } + private function createPdf(mixed $pdf, string $unit, MatrixInterface $matrix, int $labelSpace): \FPDF + { + if (null !== $pdf) { + if (!$pdf instanceof \FPDF) { + throw new \Exception('pdf option must be an instance of FPDF'); + } + + return $pdf; + } + + // @todo Check how to add label height later + $pdf = new \FPDF('P', $unit, [$matrix->getOuterSize(), $matrix->getOuterSize() + $labelSpace]); + $pdf->AddPage(); + + return $pdf; + } + + private function drawMatrix(\FPDF $fpdf, MatrixInterface $matrix, float $x, float $y): void + { + for ($rowIndex = 0; $rowIndex < $matrix->getBlockCount(); ++$rowIndex) { + for ($columnIndex = 0; $columnIndex < $matrix->getBlockCount(); ++$columnIndex) { + if (1 !== $matrix->getBlockValue($rowIndex, $columnIndex)) { + continue; + } + + $fpdf->Rect( + $x + $matrix->getMarginLeft() + ($columnIndex * $matrix->getBlockSize()), + $y + $matrix->getMarginLeft() + ($rowIndex * $matrix->getBlockSize()), + $matrix->getBlockSize(), + $matrix->getBlockSize(), + 'F', + ); + } + } + } + + private function addLabel(LabelInterface $label, \FPDF $fpdf, float $x, float $y, float $width): void + { + $fpdf->SetXY($x, $y); + $fpdf->SetFont('Helvetica', '', $label->getFont()->getSize()); + $fpdf->Cell($width, 0, $label->getText(), 0, 0, 'C'); + } + private function addLogo(LogoInterface $logo, \FPDF $fpdf, float $x, float $y, float $size): void { $logoPath = $logo->getPath(); @@ -131,8 +159,8 @@ private function addLogo(LogoInterface $logo, \FPDF $fpdf, float $x, float $y, f } } - $logoX = $x + $size / 2 - $logoWidth / 2; - $logoY = $y + $size / 2 - $logoHeight / 2; + $logoX = $x + ($size / 2) - ($logoWidth / 2); + $logoY = $y + ($size / 2) - ($logoHeight / 2); $fpdf->Image($logoPath, $logoX, $logoY, $logoWidth, $logoHeight); } diff --git a/src/Writer/PngWriter.php b/src/Writer/PngWriter.php index 1f6a51bc..fba5fc59 100644 --- a/src/Writer/PngWriter.php +++ b/src/Writer/PngWriter.php @@ -14,19 +14,24 @@ { use GdTrait; - public const WRITER_OPTION_COMPRESSION_LEVEL = 'compression_level'; - public const WRITER_OPTION_NUMBER_OF_COLORS = 'number_of_colors'; - - public function write(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?LabelInterface $label = null, array $options = []): ResultInterface - { - if (!isset($options[self::WRITER_OPTION_COMPRESSION_LEVEL])) { - $options[self::WRITER_OPTION_COMPRESSION_LEVEL] = -1; - } + public const string WRITER_OPTION_COMPRESSION_LEVEL = 'compression_level'; + public const string WRITER_OPTION_NUMBER_OF_COLORS = 'number_of_colors'; + + #[\Override] + public function write( + QrCodeInterface $qrCode, + ?LogoInterface $logo = null, + ?LabelInterface $label = null, + array $options = [], + ): ResultInterface { + /** @var array{compression_level?: int|null, number_of_colors?: int|null} $options */ + $options[self::WRITER_OPTION_COMPRESSION_LEVEL] ??= -1; if (!array_key_exists(self::WRITER_OPTION_NUMBER_OF_COLORS, $options)) { $options[self::WRITER_OPTION_NUMBER_OF_COLORS] = match (true) { - $qrCode->getBackgroundColor()->getAlpha() > 0 || $qrCode->getForegroundColor()->getAlpha() > 0 => null, - $logo instanceof LogoInterface => null, + $qrCode->getBackgroundColor()->getAlpha() > 0 || $qrCode->getForegroundColor()->getAlpha() > 0, + $logo instanceof LogoInterface, + => null, default => 16, }; } @@ -37,7 +42,7 @@ public function write(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?Lab $gdResult->getMatrix(), $gdResult->getImage(), $options[self::WRITER_OPTION_COMPRESSION_LEVEL], - $options[self::WRITER_OPTION_NUMBER_OF_COLORS] + $options[self::WRITER_OPTION_NUMBER_OF_COLORS], ); } } diff --git a/src/Writer/Result/AbstractResult.php b/src/Writer/Result/AbstractResult.php index b6547d26..cf598ef7 100644 --- a/src/Writer/Result/AbstractResult.php +++ b/src/Writer/Result/AbstractResult.php @@ -10,19 +10,21 @@ abstract class AbstractResult implements ResultInterface { public function __construct( private readonly MatrixInterface $matrix, - ) { - } + ) {} + #[\Override] public function getMatrix(): MatrixInterface { return $this->matrix; } + #[\Override] public function getDataUri(): string { - return 'data:'.$this->getMimeType().';base64,'.base64_encode($this->getString()); + return 'data:' . $this->getMimeType() . ';base64,' . base64_encode($this->getString()); } + #[\Override] public function saveToFile(string $path): void { $string = $this->getString(); diff --git a/src/Writer/Result/BinaryResult.php b/src/Writer/Result/BinaryResult.php index 386fb6a0..0587ce14 100644 --- a/src/Writer/Result/BinaryResult.php +++ b/src/Writer/Result/BinaryResult.php @@ -13,6 +13,7 @@ public function __construct(MatrixInterface $matrix) parent::__construct($matrix); } + #[\Override] public function getString(): string { $matrix = $this->getMatrix(); @@ -28,6 +29,7 @@ public function getString(): string return $binaryString; } + #[\Override] public function getMimeType(): string { return 'text/plain'; diff --git a/src/Writer/Result/ConsoleResult.php b/src/Writer/Result/ConsoleResult.php index d3644dbb..891a67e0 100644 --- a/src/Writer/Result/ConsoleResult.php +++ b/src/Writer/Result/ConsoleResult.php @@ -9,7 +9,7 @@ final class ConsoleResult extends AbstractResult { - private const TWO_BLOCKS = [ + private const array TWO_BLOCKS = [ 0 => ' ', 1 => "\xe2\x96\x80", 2 => "\xe2\x96\x84", @@ -18,11 +18,8 @@ final class ConsoleResult extends AbstractResult private string $colorEscapeCode; - public function __construct( - MatrixInterface $matrix, - ColorInterface $foreground, - ColorInterface $background, - ) { + public function __construct(MatrixInterface $matrix, ColorInterface $foreground, ColorInterface $background) + { parent::__construct($matrix); $this->colorEscapeCode = sprintf( @@ -32,33 +29,40 @@ public function __construct( $foreground->getBlue(), $background->getRed(), $background->getGreen(), - $background->getBlue() + $background->getBlue(), ); } + #[\Override] public function getMimeType(): string { return 'text/plain'; } + #[\Override] public function getString(): string { $matrix = $this->getMatrix(); $side = $matrix->getBlockCount(); - $marginLeft = $this->colorEscapeCode.self::TWO_BLOCKS[0].self::TWO_BLOCKS[0]; - $marginRight = self::TWO_BLOCKS[0].self::TWO_BLOCKS[0]."\e[0m".PHP_EOL; - $marginVertical = $marginLeft.str_repeat(self::TWO_BLOCKS[0], $side).$marginRight; + $marginLeft = $this->colorEscapeCode . self::TWO_BLOCKS[0] . self::TWO_BLOCKS[0]; + $marginRight = self::TWO_BLOCKS[0] . self::TWO_BLOCKS[0] . "\e[0m" . PHP_EOL; + $marginVertical = $marginLeft . str_repeat(self::TWO_BLOCKS[0], $side) . $marginRight; $qrCodeString = $marginVertical; for ($rowIndex = 0; $rowIndex < $side; $rowIndex += 2) { $qrCodeString .= $marginLeft; for ($columnIndex = 0; $columnIndex < $side; ++$columnIndex) { $combined = $matrix->getBlockValue($rowIndex, $columnIndex); - if ($rowIndex + 1 < $side) { + if (($rowIndex + 1) < $side) { $combined |= $matrix->getBlockValue($rowIndex + 1, $columnIndex) << 1; } - $qrCodeString .= self::TWO_BLOCKS[$combined]; + $qrCodeString .= match ($combined) { + 0 => self::TWO_BLOCKS[0], + 1 => self::TWO_BLOCKS[1], + 2 => self::TWO_BLOCKS[2], + 3 => self::TWO_BLOCKS[3], + }; } $qrCodeString .= $marginRight; } diff --git a/src/Writer/Result/DebugResult.php b/src/Writer/Result/DebugResult.php index b632993c..5557ee2d 100644 --- a/src/Writer/Result/DebugResult.php +++ b/src/Writer/Result/DebugResult.php @@ -29,44 +29,46 @@ public function setValidateResult(bool $validateResult): void $this->validateResult = $validateResult; } + #[\Override] public function getString(): string { $debugLines = []; - $debugLines[] = 'Data: '.$this->qrCode->getData(); - $debugLines[] = 'Encoding: '.$this->qrCode->getEncoding(); - $debugLines[] = 'Error Correction Level: '.get_class($this->qrCode->getErrorCorrectionLevel()); - $debugLines[] = 'Size: '.$this->qrCode->getSize(); - $debugLines[] = 'Margin: '.$this->qrCode->getMargin(); - $debugLines[] = 'Round block size mode: '.get_class($this->qrCode->getRoundBlockSizeMode()); - $debugLines[] = 'Foreground color: ['.implode(', ', $this->qrCode->getForegroundColor()->toArray()).']'; - $debugLines[] = 'Background color: ['.implode(', ', $this->qrCode->getBackgroundColor()->toArray()).']'; + $debugLines[] = 'Data: ' . $this->qrCode->getData(); + $debugLines[] = 'Encoding: ' . strval($this->qrCode->getEncoding()); + $debugLines[] = 'Error Correction Level: ' . get_class($this->qrCode->getErrorCorrectionLevel()); + $debugLines[] = 'Size: ' . $this->qrCode->getSize(); + $debugLines[] = 'Margin: ' . $this->qrCode->getMargin(); + $debugLines[] = 'Round block size mode: ' . get_class($this->qrCode->getRoundBlockSizeMode()); + $debugLines[] = 'Foreground color: [' . implode(', ', $this->qrCode->getForegroundColor()->toArray()) . ']'; + $debugLines[] = 'Background color: [' . implode(', ', $this->qrCode->getBackgroundColor()->toArray()) . ']'; - foreach ($this->options as $key => $value) { - $debugLines[] = 'Writer option: '.$key.': '.$value; + foreach (array_keys($this->options) as $key) { + $debugLines[] = 'Writer option: ' . $key . ': ' . strval($this->options[$key] ?? null); } - if (isset($this->logo)) { - $debugLines[] = 'Logo path: '.$this->logo->getPath(); - $debugLines[] = 'Logo resize to width: '.$this->logo->getResizeToWidth(); - $debugLines[] = 'Logo resize to height: '.$this->logo->getResizeToHeight(); - $debugLines[] = 'Logo punchout background: '.($this->logo->getPunchoutBackground() ? 'true' : 'false'); + if (null !== $this->logo) { + $debugLines[] = 'Logo path: ' . $this->logo->getPath(); + $debugLines[] = 'Logo resize to width: ' . strval($this->logo->getResizeToWidth()); + $debugLines[] = 'Logo resize to height: ' . strval($this->logo->getResizeToHeight()); + $debugLines[] = 'Logo punchout background: ' . ($this->logo->getPunchoutBackground() ? 'true' : 'false'); } - if (isset($this->label)) { - $debugLines[] = 'Label text: '.$this->label->getText(); - $debugLines[] = 'Label font path: '.$this->label->getFont()->getPath(); - $debugLines[] = 'Label font size: '.$this->label->getFont()->getSize(); - $debugLines[] = 'Label alignment: '.get_class($this->label->getAlignment()); - $debugLines[] = 'Label margin: ['.implode(', ', $this->label->getMargin()->toArray()).']'; - $debugLines[] = 'Label text color: ['.implode(', ', $this->label->getTextColor()->toArray()).']'; + if (null !== $this->label) { + $debugLines[] = 'Label text: ' . $this->label->getText(); + $debugLines[] = 'Label font path: ' . $this->label->getFont()->getPath(); + $debugLines[] = 'Label font size: ' . $this->label->getFont()->getSize(); + $debugLines[] = 'Label alignment: ' . get_class($this->label->getAlignment()); + $debugLines[] = 'Label margin: [' . implode(', ', $this->label->getMargin()->toArray()) . ']'; + $debugLines[] = 'Label text color: [' . implode(', ', $this->label->getTextColor()->toArray()) . ']'; } - $debugLines[] = 'Validate result: '.($this->validateResult ? 'true' : 'false'); + $debugLines[] = 'Validate result: ' . ($this->validateResult ? 'true' : 'false'); return implode("\n", $debugLines); } + #[\Override] public function getMimeType(): string { return 'text/plain'; diff --git a/src/Writer/Result/EpsResult.php b/src/Writer/Result/EpsResult.php index d801fd6e..25912112 100644 --- a/src/Writer/Result/EpsResult.php +++ b/src/Writer/Result/EpsResult.php @@ -16,11 +16,13 @@ public function __construct( parent::__construct($matrix); } + #[\Override] public function getString(): string { return implode("\n", $this->lines); } + #[\Override] public function getMimeType(): string { return 'image/eps'; diff --git a/src/Writer/Result/GdResult.php b/src/Writer/Result/GdResult.php index a58c3e40..1b6d8597 100644 --- a/src/Writer/Result/GdResult.php +++ b/src/Writer/Result/GdResult.php @@ -20,11 +20,13 @@ public function getImage(): \GdImage return $this->image; } + #[\Override] public function getString(): string { throw new \Exception('You can only use this method in a concrete implementation'); } + #[\Override] public function getMimeType(): string { throw new \Exception('You can only use this method in a concrete implementation'); diff --git a/src/Writer/Result/GifResult.php b/src/Writer/Result/GifResult.php index 84b24971..02f90f75 100644 --- a/src/Writer/Result/GifResult.php +++ b/src/Writer/Result/GifResult.php @@ -6,6 +6,7 @@ final class GifResult extends GdResult { + #[\Override] public function getString(): string { ob_start(); @@ -14,6 +15,7 @@ public function getString(): string return strval(ob_get_clean()); } + #[\Override] public function getMimeType(): string { return 'image/gif'; diff --git a/src/Writer/Result/PdfResult.php b/src/Writer/Result/PdfResult.php index f7746a20..e3e09da2 100644 --- a/src/Writer/Result/PdfResult.php +++ b/src/Writer/Result/PdfResult.php @@ -20,11 +20,19 @@ public function getPdf(): \FPDF return $this->fpdf; } + #[\Override] public function getString(): string { - return $this->fpdf->Output('S'); + /** @var mixed $output FPDF has no declared return type; destination S must return document data. */ + $output = $this->fpdf->Output('S'); + if (!is_string($output)) { + throw new \TypeError('FPDF did not return document data'); + } + + return $output; } + #[\Override] public function getMimeType(): string { return 'application/pdf'; diff --git a/src/Writer/Result/PngResult.php b/src/Writer/Result/PngResult.php index 8cdbc53b..b3adb85b 100644 --- a/src/Writer/Result/PngResult.php +++ b/src/Writer/Result/PngResult.php @@ -17,17 +17,19 @@ public function __construct( parent::__construct($matrix, $image); } + #[\Override] public function getString(): string { ob_start(); if (null !== $this->numberOfColors) { - imagetruecolortopalette($this->image, false, $this->numberOfColors); + imagetruecolortopalette($this->image, dither: false, num_colors: $this->numberOfColors); } imagepng($this->image, quality: $this->quality); return strval(ob_get_clean()); } + #[\Override] public function getMimeType(): string { return 'image/png'; diff --git a/src/Writer/Result/SvgResult.php b/src/Writer/Result/SvgResult.php index 2c9d2819..d98cf874 100644 --- a/src/Writer/Result/SvgResult.php +++ b/src/Writer/Result/SvgResult.php @@ -21,6 +21,7 @@ public function getXml(): \SimpleXMLElement return $this->xml; } + #[\Override] public function getString(): string { $string = $this->xml->asXML(); @@ -30,12 +31,13 @@ public function getString(): string } if ($this->excludeXmlDeclaration) { - $string = str_replace("\n", '', $string); + $string = str_replace("\n", replace: '', subject: $string); } return $string; } + #[\Override] public function getMimeType(): string { return 'image/svg+xml'; diff --git a/src/Writer/Result/WebPResult.php b/src/Writer/Result/WebPResult.php index 735f1284..af86bc92 100644 --- a/src/Writer/Result/WebPResult.php +++ b/src/Writer/Result/WebPResult.php @@ -16,6 +16,7 @@ public function __construct( parent::__construct($matrix, $image); } + #[\Override] public function getString(): string { if (!function_exists('imagewebp')) { @@ -28,6 +29,7 @@ public function getString(): string return strval(ob_get_clean()); } + #[\Override] public function getMimeType(): string { return 'image/webp'; diff --git a/src/Writer/SvgWriter.php b/src/Writer/SvgWriter.php index 9001279e..3ec08eb7 100644 --- a/src/Writer/SvgWriter.php +++ b/src/Writer/SvgWriter.php @@ -5,6 +5,7 @@ namespace Endroid\QrCode\Writer; use Endroid\QrCode\Bacon\MatrixFactory; +use Endroid\QrCode\Color\ColorInterface; use Endroid\QrCode\ImageData\LogoImageData; use Endroid\QrCode\Label\LabelInterface; use Endroid\QrCode\Logo\LogoInterface; @@ -15,53 +16,52 @@ final readonly class SvgWriter implements WriterInterface { - public const DECIMAL_PRECISION = 2; - public const WRITER_OPTION_COMPACT = 'compact'; - public const WRITER_OPTION_BLOCK_ID = 'block_id'; - public const WRITER_OPTION_EXCLUDE_XML_DECLARATION = 'exclude_xml_declaration'; - public const WRITER_OPTION_EXCLUDE_SVG_WIDTH_AND_HEIGHT = 'exclude_svg_width_and_height'; - public const WRITER_OPTION_FORCE_XLINK_HREF = 'force_xlink_href'; - - public function write(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?LabelInterface $label = null, array $options = []): ResultInterface - { - if (!isset($options[self::WRITER_OPTION_COMPACT])) { - $options[self::WRITER_OPTION_COMPACT] = true; - } - - if (!isset($options[self::WRITER_OPTION_BLOCK_ID])) { - $options[self::WRITER_OPTION_BLOCK_ID] = 'block'; - } - - if (!isset($options[self::WRITER_OPTION_EXCLUDE_XML_DECLARATION])) { - $options[self::WRITER_OPTION_EXCLUDE_XML_DECLARATION] = false; - } - - if (!isset($options[self::WRITER_OPTION_EXCLUDE_SVG_WIDTH_AND_HEIGHT])) { - $options[self::WRITER_OPTION_EXCLUDE_SVG_WIDTH_AND_HEIGHT] = false; - } + public const int DECIMAL_PRECISION = 2; + public const string WRITER_OPTION_COMPACT = 'compact'; + public const string WRITER_OPTION_BLOCK_ID = 'block_id'; + public const string WRITER_OPTION_EXCLUDE_XML_DECLARATION = 'exclude_xml_declaration'; + public const string WRITER_OPTION_EXCLUDE_SVG_WIDTH_AND_HEIGHT = 'exclude_svg_width_and_height'; + public const string WRITER_OPTION_FORCE_XLINK_HREF = 'force_xlink_href'; + + #[\Override] + public function write( + QrCodeInterface $qrCode, + ?LogoInterface $logo = null, + ?LabelInterface $label = null, + array $options = [], + ): ResultInterface { + $options[self::WRITER_OPTION_COMPACT] ??= true; + $options[self::WRITER_OPTION_BLOCK_ID] ??= 'block'; + $options[self::WRITER_OPTION_EXCLUDE_XML_DECLARATION] ??= false; + $options[self::WRITER_OPTION_EXCLUDE_SVG_WIDTH_AND_HEIGHT] ??= false; $matrixFactory = new MatrixFactory(); $matrix = $matrixFactory->create($qrCode); - $xml = new \SimpleXMLElement(''); + $xml = new \SimpleXMLElement( + '', + ); $xml->addAttribute('version', '1.1'); if (!$options[self::WRITER_OPTION_EXCLUDE_SVG_WIDTH_AND_HEIGHT]) { - $xml->addAttribute('width', $matrix->getOuterSize().'px'); - $xml->addAttribute('height', $matrix->getOuterSize().'px'); + $xml->addAttribute('width', $matrix->getOuterSize() . 'px'); + $xml->addAttribute('height', $matrix->getOuterSize() . 'px'); } - $xml->addAttribute('viewBox', '0 0 '.$matrix->getOuterSize().' '.$matrix->getOuterSize()); + $xml->addAttribute('viewBox', '0 0 ' . $matrix->getOuterSize() . ' ' . $matrix->getOuterSize()); + // These fixed, valid element names always produce a child element. + /** @var \SimpleXMLElement $background */ $background = $xml->addChild('rect'); $background->addAttribute('x', '0'); $background->addAttribute('y', '0'); $background->addAttribute('width', strval($matrix->getOuterSize())); $background->addAttribute('height', strval($matrix->getOuterSize())); - $background->addAttribute('fill', '#'.sprintf('%02x%02x%02x', $qrCode->getBackgroundColor()->getRed(), $qrCode->getBackgroundColor()->getGreen(), $qrCode->getBackgroundColor()->getBlue())); + $background->addAttribute('fill', $this->formatColor($qrCode->getBackgroundColor())); $background->addAttribute('fill-opacity', strval($qrCode->getBackgroundColor()->getOpacity())); if ($options[self::WRITER_OPTION_COMPACT]) { $this->writePath($xml, $qrCode, $matrix); - } else { + } + if (!$options[self::WRITER_OPTION_COMPACT]) { $this->writeBlockDefinitions($xml, $qrCode, $matrix, $options); } @@ -80,51 +80,72 @@ private function writePath(\SimpleXMLElement $xml, QrCodeInterface $qrCode, Matr for ($rowIndex = 0; $rowIndex < $matrix->getBlockCount(); ++$rowIndex) { $left = $matrix->getMarginLeft(); for ($columnIndex = 0; $columnIndex < $matrix->getBlockCount(); ++$columnIndex) { - if (1 === $matrix->getBlockValue($rowIndex, $columnIndex)) { - // When we are at the first column or when the previous column was 0 set new left - if (0 === $columnIndex || 0 === $matrix->getBlockValue($rowIndex, $columnIndex - 1)) { - $left = $matrix->getMarginLeft() + $matrix->getBlockSize() * $columnIndex; - } - // When we are at the - if ($columnIndex === $matrix->getBlockCount() - 1 || 0 === $matrix->getBlockValue($rowIndex, $columnIndex + 1)) { - $top = $matrix->getMarginLeft() + $matrix->getBlockSize() * $rowIndex; - $bottom = $matrix->getMarginLeft() + $matrix->getBlockSize() * ($rowIndex + 1); - $right = $matrix->getMarginLeft() + $matrix->getBlockSize() * ($columnIndex + 1); - $path .= 'M'.$this->formatNumber($left).','.$this->formatNumber($top); - $path .= 'L'.$this->formatNumber($right).','.$this->formatNumber($top); - $path .= 'L'.$this->formatNumber($right).','.$this->formatNumber($bottom); - $path .= 'L'.$this->formatNumber($left).','.$this->formatNumber($bottom).'Z'; - } + if (1 !== $matrix->getBlockValue($rowIndex, $columnIndex)) { + continue; + } + + // When we are at the first column or when the previous column was 0 set new left + if (0 === $columnIndex || 0 === $matrix->getBlockValue($rowIndex, $columnIndex - 1)) { + $left = $matrix->getMarginLeft() + ($matrix->getBlockSize() * $columnIndex); + } + // Close the rectangle at the end of a run of dark modules. + if ( + $columnIndex === ($matrix->getBlockCount() - 1) + || 0 === $matrix->getBlockValue($rowIndex, $columnIndex + 1) + ) { + $top = $matrix->getMarginLeft() + ($matrix->getBlockSize() * $rowIndex); + $bottom = $matrix->getMarginLeft() + ($matrix->getBlockSize() * ($rowIndex + 1)); + $right = $matrix->getMarginLeft() + ($matrix->getBlockSize() * ($columnIndex + 1)); + $path .= $this->createRectanglePath($left, $top, $right, $bottom); } } } + /** @var \SimpleXMLElement $pathDefinition */ $pathDefinition = $xml->addChild('path'); - $pathDefinition->addAttribute('fill', '#'.sprintf('%02x%02x%02x', $qrCode->getForegroundColor()->getRed(), $qrCode->getForegroundColor()->getGreen(), $qrCode->getForegroundColor()->getBlue())); + $pathDefinition->addAttribute('fill', $this->formatColor($qrCode->getForegroundColor())); $pathDefinition->addAttribute('fill-opacity', strval($qrCode->getForegroundColor()->getOpacity())); $pathDefinition->addAttribute('d', $path); } /** @param array $options */ - private function writeBlockDefinitions(\SimpleXMLElement $xml, QrCodeInterface $qrCode, MatrixInterface $matrix, array $options): void - { - $xml->addChild('defs'); - - $blockDefinition = $xml->defs->addChild('rect'); - $blockDefinition->addAttribute('id', strval($options[self::WRITER_OPTION_BLOCK_ID])); + private function writeBlockDefinitions( + \SimpleXMLElement $xml, + QrCodeInterface $qrCode, + MatrixInterface $matrix, + array $options, + ): void { + /** @var \SimpleXMLElement $definitions */ + $definitions = $xml->addChild('defs'); + /** @var \SimpleXMLElement $blockDefinition */ + $blockDefinition = $definitions->addChild('rect'); + $blockDefinition->addAttribute('id', strval($options[self::WRITER_OPTION_BLOCK_ID] ?? 'block')); $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', $this->formatColor($qrCode->getForegroundColor())); $blockDefinition->addAttribute('fill-opacity', strval($qrCode->getForegroundColor()->getOpacity())); for ($rowIndex = 0; $rowIndex < $matrix->getBlockCount(); ++$rowIndex) { for ($columnIndex = 0; $columnIndex < $matrix->getBlockCount(); ++$columnIndex) { - if (1 === $matrix->getBlockValue($rowIndex, $columnIndex)) { - $block = $xml->addChild('use'); - $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'); + if (1 !== $matrix->getBlockValue($rowIndex, $columnIndex)) { + continue; } + + /** @var \SimpleXMLElement $block */ + $block = $xml->addChild('use'); + $block->addAttribute( + 'x', + $this->formatNumber($matrix->getMarginLeft() + ($matrix->getBlockSize() * $columnIndex)), + ); + $block->addAttribute( + 'y', + $this->formatNumber($matrix->getMarginLeft() + ($matrix->getBlockSize() * $rowIndex)), + ); + $block->addAttribute( + 'xlink:href', + '#' . strval($options[self::WRITER_OPTION_BLOCK_ID] ?? 'block'), + 'http://www.w3.org/1999/xlink', + ); } } } @@ -138,18 +159,17 @@ private function addLogo(LogoInterface $logo, SvgResult $result, array $options) $logoImageData = LogoImageData::createForLogo($logo); - if (!isset($options[self::WRITER_OPTION_FORCE_XLINK_HREF])) { - $options[self::WRITER_OPTION_FORCE_XLINK_HREF] = false; - } + $options[self::WRITER_OPTION_FORCE_XLINK_HREF] ??= false; $xml = $result->getXml(); /** @var \SimpleXMLElement $xmlAttributes */ $xmlAttributes = $xml->attributes(); - $x = intval($xmlAttributes->width) / 2 - $logoImageData->getWidth() / 2; - $y = intval($xmlAttributes->height) / 2 - $logoImageData->getHeight() / 2; + $x = (intval($xmlAttributes['width']) / 2) - ($logoImageData->getWidth() / 2); + $y = (intval($xmlAttributes['height']) / 2) - ($logoImageData->getHeight() / 2); + /** @var \SimpleXMLElement $imageDefinition */ $imageDefinition = $xml->addChild('image'); $imageDefinition->addAttribute('x', strval($x)); $imageDefinition->addAttribute('y', strval($y)); @@ -158,17 +178,50 @@ private function addLogo(LogoInterface $logo, SvgResult $result, array $options) $imageDefinition->addAttribute('preserveAspectRatio', 'none'); if ($options[self::WRITER_OPTION_FORCE_XLINK_HREF]) { - $imageDefinition->addAttribute('xlink:href', $logoImageData->createDataUri(), 'http://www.w3.org/1999/xlink'); - } else { - $imageDefinition->addAttribute('href', $logoImageData->createDataUri()); + $imageDefinition->addAttribute( + 'xlink:href', + $logoImageData->createDataUri(), + 'http://www.w3.org/1999/xlink', + ); + return; } + + $imageDefinition->addAttribute('href', $logoImageData->createDataUri()); + } + + private function createRectanglePath(float $left, float $top, float $right, float $bottom): string + { + return ( + 'M' + . $this->formatNumber($left) + . ',' + . $this->formatNumber($top) + . 'L' + . $this->formatNumber($right) + . ',' + . $this->formatNumber($top) + . 'L' + . $this->formatNumber($right) + . ',' + . $this->formatNumber($bottom) + . 'L' + . $this->formatNumber($left) + . ',' + . $this->formatNumber($bottom) + . 'Z' + ); + } + + private function formatColor(ColorInterface $color): string + { + return sprintf('#%02x%02x%02x', $color->getRed(), $color->getGreen(), $color->getBlue()); } private function formatNumber(float $number): string { - $string = number_format($number, self::DECIMAL_PRECISION, '.', ''); - $string = rtrim($string, '0'); + $string = number_format($number, self::DECIMAL_PRECISION, decimal_separator: '.', thousands_separator: ''); + $string = rtrim($string, characters: '0'); - return rtrim($string, '.'); + return rtrim($string, characters: '.'); } } diff --git a/src/Writer/WebPWriter.php b/src/Writer/WebPWriter.php index 90438904..2f04cd4d 100644 --- a/src/Writer/WebPWriter.php +++ b/src/Writer/WebPWriter.php @@ -14,13 +14,17 @@ { use GdTrait; - public const WRITER_OPTION_QUALITY = 'quality'; - - public function write(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?LabelInterface $label = null, array $options = []): ResultInterface - { - if (!isset($options[self::WRITER_OPTION_QUALITY])) { - $options[self::WRITER_OPTION_QUALITY] = -1; - } + public const string WRITER_OPTION_QUALITY = 'quality'; + + #[\Override] + public function write( + QrCodeInterface $qrCode, + ?LogoInterface $logo = null, + ?LabelInterface $label = null, + array $options = [], + ): ResultInterface { + /** @var array{quality?: int|null} $options */ + $options[self::WRITER_OPTION_QUALITY] ??= -1; $gdResult = $this->writeGd($qrCode, $logo, $label, $options); diff --git a/src/Writer/WriterInterface.php b/src/Writer/WriterInterface.php index 66b233f9..732757c3 100644 --- a/src/Writer/WriterInterface.php +++ b/src/Writer/WriterInterface.php @@ -12,5 +12,10 @@ interface WriterInterface { /** @param array $options */ - public function write(QrCodeInterface $qrCode, ?LogoInterface $logo = null, ?LabelInterface $label = null, array $options = []): ResultInterface; + public function write( + QrCodeInterface $qrCode, + ?LogoInterface $logo = null, + ?LabelInterface $label = null, + array $options = [], + ): ResultInterface; } diff --git a/tests/WriterRenderingTest.php b/tests/WriterRenderingTest.php new file mode 100644 index 00000000..79703a68 --- /dev/null +++ b/tests/WriterRenderingTest.php @@ -0,0 +1,101 @@ +write($qrCode); + $xml = new \SimpleXMLElement($result->getString()); + + // The first finder-pattern run spans seven modules at fractional block size. + $this->assertStringStartsWith('M11,11L111.33,11L111.33,25.33L11,25.33Z', (string) $xml->path['d']); + $this->assertSame('#17436d', (string) $xml->path['fill']); + $this->assertSame((string) $qrCode->getForegroundColor()->getOpacity(), (string) $xml->path['fill-opacity']); + } + + public function testEpsPreservesColorFormattingAndCoordinatePrecision(): void + { + $qrCode = new QrCode( + data: 'QR Code', + size: 301, + margin: 11, + roundBlockSizeMode: RoundBlockSizeMode::None, + foregroundColor: new Color(23, 67, 109), + backgroundColor: new Color(237, 241, 249) + ); + + $lines = explode("\n", (new EpsWriter())->write($qrCode)->getString()); + + $this->assertSame('2.37 2.41 2.49 setrgbcolor', $lines[3]); + $this->assertSame('0.23 0.67 1.09 setrgbcolor', $lines[5]); + $this->assertSame('11.0000000000 11.0000000000 14.3333333333 14.3333333333 F', $lines[6]); + } + + public function testNullWriterOptionsRetainDefaults(): void + { + $qrCode = new QrCode('QR Code'); + $cases = [ + [new PngWriter(), ['compression_level' => null]], + [new WebPWriter(), ['quality' => null]], + [new SvgWriter(), ['compact' => null, 'block_id' => null, 'exclude_xml_declaration' => null, 'exclude_svg_width_and_height' => null]], + ]; + + foreach ($cases as [$writer, $options]) { + $this->assertSame($writer->write($qrCode)->getString(), $writer->write($qrCode, options: $options)->getString()); + } + } + + public function testExplicitNullPngPaletteOptionKeepsTrueColor(): void + { + $writer = new PngWriter(); + $qrCode = new QrCode('QR Code'); + $palette = imagecreatefromstring($writer->write($qrCode)->getString()); + $trueColor = imagecreatefromstring($writer->write($qrCode, options: ['number_of_colors' => null])->getString()); + + $this->assertFalse(imageistruecolor($palette)); + $this->assertTrue(imageistruecolor($trueColor)); + } + + public function testPdfUsesExistingDocumentWithoutAddingPage(): void + { + $pdf = new \FPDF(); + $pdf->AddPage(); + $pdf->SetXY(5, 5); + $pdf->SetFont('Helvetica', '', 12); + $pdf->Cell(20, 5, 'Existing content'); + + $result = (new PdfWriter())->write(new QrCode('QR Code'), options: [ + 'fpdf' => $pdf, + 'unit' => null, + 'x' => 7, + 'y' => 11, + 'link' => 'https://example.com', + ]); + + $this->assertSame($pdf, $result->getPdf()); + $this->assertSame(1, $pdf->PageNo()); + $this->assertStringContainsString('/URI (https://example.com)', $result->getString()); + } +}