WriterRegistry.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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\PngWriter;
  15. use Endroid\QrCode\Writer\SvgWriter;
  16. use Endroid\QrCode\Writer\WriterInterface;
  17. class WriterRegistry implements WriterRegistryInterface
  18. {
  19. /** @var WriterInterface[] */
  20. private $writers = [];
  21. /** @var WriterInterface|null */
  22. private $defaultWriter;
  23. public function loadDefaultWriters(): void
  24. {
  25. if (count($this->writers) > 0) {
  26. return;
  27. }
  28. $this->addWriters([
  29. new BinaryWriter(),
  30. new DebugWriter(),
  31. new EpsWriter(),
  32. new PngWriter(),
  33. new SvgWriter(),
  34. ]);
  35. $this->setDefaultWriter('png');
  36. }
  37. public function addWriters(iterable $writers): void
  38. {
  39. foreach ($writers as $writer) {
  40. $this->addWriter($writer);
  41. }
  42. }
  43. public function addWriter(WriterInterface $writer): void
  44. {
  45. $this->writers[$writer->getName()] = $writer;
  46. }
  47. public function getWriter(string $name): WriterInterface
  48. {
  49. $this->assertValidWriter($name);
  50. return $this->writers[$name];
  51. }
  52. public function getDefaultWriter(): WriterInterface
  53. {
  54. if ($this->defaultWriter instanceof WriterInterface) {
  55. return $this->defaultWriter;
  56. }
  57. throw new InvalidWriterException('Please set the default writer via the second argument of addWriter');
  58. }
  59. public function setDefaultWriter(string $name): void
  60. {
  61. $this->defaultWriter = $this->writers[$name];
  62. }
  63. public function getWriters(): array
  64. {
  65. return $this->writers;
  66. }
  67. private function assertValidWriter(string $name): void
  68. {
  69. if (!isset($this->writers[$name])) {
  70. throw new InvalidWriterException('Invalid writer "'.$name.'"');
  71. }
  72. }
  73. }