WriterRegistry.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * (c) Jeroen van den Enden <info@endroid.nl>
  5. *
  6. * This source file is subject to the MIT license that is bundled
  7. * with this source code in the file LICENSE.
  8. */
  9. namespace Endroid\QrCode;
  10. use Endroid\QrCode\Exception\InvalidWriterException;
  11. use Endroid\QrCode\Writer\BinaryWriter;
  12. use Endroid\QrCode\Writer\DebugWriter;
  13. use Endroid\QrCode\Writer\EpsWriter;
  14. use Endroid\QrCode\Writer\FpdfWriter;
  15. use Endroid\QrCode\Writer\PngWriter;
  16. use Endroid\QrCode\Writer\SvgWriter;
  17. use Endroid\QrCode\Writer\WriterInterface;
  18. class WriterRegistry implements WriterRegistryInterface
  19. {
  20. /** @var WriterInterface[] */
  21. private $writers = [];
  22. /** @var WriterInterface|null */
  23. private $defaultWriter;
  24. public function loadDefaultWriters(): void
  25. {
  26. if (count($this->writers) > 0) {
  27. return;
  28. }
  29. $this->addWriters([
  30. new BinaryWriter(),
  31. new DebugWriter(),
  32. new EpsWriter(),
  33. new PngWriter(),
  34. new SvgWriter(),
  35. new FpdfWriter(),
  36. ]);
  37. $this->setDefaultWriter('png');
  38. }
  39. public function addWriters(iterable $writers): void
  40. {
  41. foreach ($writers as $writer) {
  42. $this->addWriter($writer);
  43. }
  44. }
  45. public function addWriter(WriterInterface $writer): void
  46. {
  47. $this->writers[$writer->getName()] = $writer;
  48. }
  49. public function getWriter(string $name): WriterInterface
  50. {
  51. $this->assertValidWriter($name);
  52. return $this->writers[$name];
  53. }
  54. public function getDefaultWriter(): WriterInterface
  55. {
  56. if ($this->defaultWriter instanceof WriterInterface) {
  57. return $this->defaultWriter;
  58. }
  59. throw new InvalidWriterException('Please set the default writer via the second argument of addWriter');
  60. }
  61. public function setDefaultWriter(string $name): void
  62. {
  63. $this->defaultWriter = $this->writers[$name];
  64. }
  65. public function getWriters(): array
  66. {
  67. return $this->writers;
  68. }
  69. private function assertValidWriter(string $name): void
  70. {
  71. if (!isset($this->writers[$name])) {
  72. throw new InvalidWriterException('Invalid writer "'.$name.'"');
  73. }
  74. }
  75. }