AbstractWriter.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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\Writer;
  10. use Endroid\QrCode\Exception\GenerateImageException;
  11. use Endroid\QrCode\Exception\InvalidLogoException;
  12. use Endroid\QrCode\Exception\MissingExtensionException;
  13. use Endroid\QrCode\QrCodeInterface;
  14. abstract class AbstractWriter implements WriterInterface
  15. {
  16. protected function getMimeType(string $path): string
  17. {
  18. if (!function_exists('mime_content_type')) {
  19. throw new MissingExtensionException('You need the ext-fileinfo extension to determine logo mime type');
  20. }
  21. $mimeType = mime_content_type($path);
  22. if (!is_string($mimeType)) {
  23. throw new InvalidLogoException('Could not determine mime type');
  24. }
  25. if (!preg_match('#^image/#', $mimeType)) {
  26. throw new GenerateImageException('Logo path is not an image');
  27. }
  28. // Passing mime type image/svg results in invisible images
  29. if ('image/svg' === $mimeType) {
  30. return 'image/svg+xml';
  31. }
  32. return $mimeType;
  33. }
  34. public function writeDataUri(QrCodeInterface $qrCode): string
  35. {
  36. $dataUri = 'data:'.$this->getContentType().';base64,'.base64_encode($this->writeString($qrCode));
  37. return $dataUri;
  38. }
  39. public function writeFile(QrCodeInterface $qrCode, string $path): void
  40. {
  41. $string = $this->writeString($qrCode);
  42. file_put_contents($path, $string);
  43. }
  44. public static function supportsExtension(string $extension): bool
  45. {
  46. return in_array($extension, static::getSupportedExtensions());
  47. }
  48. public static function getSupportedExtensions(): array
  49. {
  50. return [];
  51. }
  52. abstract public function getName(): string;
  53. }