Writer.php 1.7 KB

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