Writer.php 1.8 KB

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