Debian Codegraph @

src/Writer.php

raw
1 <?php
2 declare(strict_types = 1);
3
4 namespace BaconQrCode;
5
6 use BaconQrCode\Common\ErrorCorrectionLevel;
7 use BaconQrCode\Common\Version;
8 use BaconQrCode\Encoder\Encoder;
9 use BaconQrCode\Exception\InvalidArgumentException;
10 use BaconQrCode\Renderer\RendererInterface;
11
12 /**
13 * QR code writer.
14 */
15 final class Writer
16 {
17 /**
18 * Creates a new writer with a specific renderer.
19 */
20 public function __construct(private readonly RendererInterface $renderer)
21 {
22 }
23
24 /**
25 * Writes QR code and returns it as string.
26 *
27 * Content is a string which *should* be encoded in UTF-8, in case there are
28 * non ASCII-characters present.
29 *
30 * @throws InvalidArgumentException if the content is empty
31 */
32 public function writeString(
33 string $content,
34 string $encoding = Encoder::DEFAULT_BYTE_MODE_ENCODING,
35 ?ErrorCorrectionLevel $ecLevel = null,
36 ?Version $forcedVersion = null
37 ) : string {
38 if (strlen($content) === 0) {
39 throw new InvalidArgumentException('Found empty contents');
40 }
41
42 if (null === $ecLevel) {
43 $ecLevel = ErrorCorrectionLevel::L();
44 }
45
46 return $this->renderer->render(Encoder::encode($content, $ecLevel, $encoding, $forcedVersion));
47 }
48
49 /**
50 * Writes QR code to a file.
51 *
52 * @see Writer::writeString()
53 */
54 public function writeFile(
55 string $content,
56 string $filename,
57 string $encoding = Encoder::DEFAULT_BYTE_MODE_ENCODING,
58 ?ErrorCorrectionLevel $ecLevel = null,
59 ?Version $forcedVersion = null
60 ) : void {
61 file_put_contents($filename, $this->writeString($content, $encoding, $ecLevel, $forcedVersion));
62 }
63 }