|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Sentry\Attachment; |
| 6 | + |
| 7 | +abstract class Attachment |
| 8 | +{ |
| 9 | + private const DEFAULT_CONTENT_TYPE = 'application/octet-stream'; |
| 10 | + |
| 11 | + /** |
| 12 | + * @var string |
| 13 | + */ |
| 14 | + private $filename; |
| 15 | + |
| 16 | + /** |
| 17 | + * @var string |
| 18 | + */ |
| 19 | + private $contentType; |
| 20 | + |
| 21 | + public function __construct(string $filename, string $contentType) |
| 22 | + { |
| 23 | + $this->filename = $filename; |
| 24 | + $this->contentType = $contentType; |
| 25 | + } |
| 26 | + |
| 27 | + public function getFilename(): string |
| 28 | + { |
| 29 | + return $this->filename; |
| 30 | + } |
| 31 | + |
| 32 | + public function getContentType(): string |
| 33 | + { |
| 34 | + return $this->contentType; |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Returns the size in bytes for the attachment. This method should aim to use a low overhead |
| 39 | + * way of determining the size because it will be called more than once. |
| 40 | + * For example, for file attachments it should read the file size from the filesystem instead of |
| 41 | + * reading the file in memory and then calculating the length. |
| 42 | + * If no low overhead way exists, then the result should be cached so that calling it multiple times |
| 43 | + * does not decrease performance. |
| 44 | + * |
| 45 | + * @return int the size in bytes or null if the length could not be determined, for example if the file |
| 46 | + * does not exist |
| 47 | + */ |
| 48 | + abstract public function getSize(): ?int; |
| 49 | + |
| 50 | + /** |
| 51 | + * Fetches and returns the data. Calling this can have a non-trivial impact on memory usage, depending |
| 52 | + * on the type and size of attachment. |
| 53 | + * |
| 54 | + * @return string the content as bytes or null if the content could not be retrieved, for example if the file |
| 55 | + * does not exist |
| 56 | + */ |
| 57 | + abstract public function getData(): ?string; |
| 58 | + |
| 59 | + /** |
| 60 | + * Creates a new attachment representing a file referenced by a path. |
| 61 | + * The file is not validated and the content is not read when creating the attachment. |
| 62 | + */ |
| 63 | + public static function fromFile(string $path, string $contentType = self::DEFAULT_CONTENT_TYPE): Attachment |
| 64 | + { |
| 65 | + return new FileAttachment($path, $contentType); |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Creates a new attachment representing a slice of bytes that lives in memory. |
| 70 | + */ |
| 71 | + public static function fromBytes(string $filename, string $data, string $contentType = self::DEFAULT_CONTENT_TYPE): Attachment |
| 72 | + { |
| 73 | + return new ByteAttachment($filename, $contentType, $data); |
| 74 | + } |
| 75 | +} |
0 commit comments