AbstractWriter.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 (false !== filter_var($path, FILTER_VALIDATE_URL)) {
  19. return $this->getMimeTypeFromUrl($path);
  20. }
  21. return $this->getMimeTypeFromPath($path);
  22. }
  23. private function getMimeTypeFromUrl(string $url): string
  24. {
  25. /** @var mixed $format */
  26. $format = PHP_VERSION > 80000 ? true : 1;
  27. $headers = get_headers($url, $format);
  28. if (!is_array($headers) || !isset($headers['Content-Type'])) {
  29. throw new InvalidLogoException(sprintf('Content type could not be determined for logo URL "%s"', $url));
  30. }
  31. return $headers['Content-Type'];
  32. }
  33. private function getMimeTypeFromPath(string $path): string
  34. {
  35. if (!function_exists('mime_content_type')) {
  36. throw new MissingExtensionException('You need the ext-fileinfo extension to determine logo mime type');
  37. }
  38. $mimeType = mime_content_type($path);
  39. if (!is_string($mimeType)) {
  40. throw new InvalidLogoException('Could not determine mime type');
  41. }
  42. if (!preg_match('#^image/#', $mimeType)) {
  43. throw new GenerateImageException('Logo path is not an image');
  44. }
  45. // Passing mime type image/svg results in invisible images
  46. if ('image/svg' === $mimeType) {
  47. return 'image/svg+xml';
  48. }
  49. return $mimeType;
  50. }
  51. public function writeDataUri(QrCodeInterface $qrCode): string
  52. {
  53. $dataUri = 'data:'.$this->getContentType().';base64,'.base64_encode($this->writeString($qrCode));
  54. return $dataUri;
  55. }
  56. public function writeFile(QrCodeInterface $qrCode, string $path): void
  57. {
  58. $string = $this->writeString($qrCode);
  59. file_put_contents($path, $string);
  60. }
  61. public static function supportsExtension(string $extension): bool
  62. {
  63. return in_array($extension, static::getSupportedExtensions());
  64. }
  65. public static function getSupportedExtensions(): array
  66. {
  67. return [];
  68. }
  69. abstract public function getName(): string;
  70. }