From b56beba4ce00f70a95d3071e272da9d2f746166d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20P=2E?= Date: Fri, 27 Sep 2024 08:10:37 +0200 Subject: [PATCH] Add toString methods --- src/FitsHeader.php | 32 ++++++++++++++++++++++++++------ src/Keyword.php | 5 +++++ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/src/FitsHeader.php b/src/FitsHeader.php index 6a0e26f..f36c071 100644 --- a/src/FitsHeader.php +++ b/src/FitsHeader.php @@ -13,6 +13,10 @@ class FitsHeader * @var Keyword[] $keywords */ public readonly array $keywords; + /** + * @var string[] $blanks + */ + private array $blanks; public function __construct(string $headerBlock) { @@ -30,26 +34,42 @@ class FitsHeader { $records = str_split($this->headerBlock, 80); - $records = array_filter( + $filtered = array_filter( $records, fn (string $r) => trim($r) !== '' && !str_starts_with($r, 'END') ); + $this->blanks = array_diff($records, $filtered); + $keywords = []; - foreach ($records as $record) { + foreach ($filtered as $record) { $splitByComment = explode('/', $record); - $comment = isset($splitByComment[1]) ? trim($splitByComment[1]) : null; - $nameValue = explode('=', $splitByComment[0]); + $comment = isset($splitByComment[1]) ? $splitByComment[1] : null; + [$name, $value] = explode('=', $splitByComment[0]); $keywords[] = new Keyword( - name : trim($nameValue[0]), - value : trim($nameValue[1]), + name : $name, + value : $value, comment : $comment, ); } return $keywords; } + /** + * Return the FITS header as a string (byte stream) + */ + public function toString(): string + { + $blanks = implode('', $this->blanks); + $keywordsString = ''; + + foreach ($this->keywords as $keyword) { + $keywordsString .= $keyword->toString(); + } + + return $keywordsString . $blanks; + } } diff --git a/src/Keyword.php b/src/Keyword.php index 0fb55ce..a84a4ba 100644 --- a/src/Keyword.php +++ b/src/Keyword.php @@ -15,4 +15,9 @@ readonly class Keyword public string $value, public ?string $comment, ) {} + + public function toString(): string + { + return "{$this->name}={$this->value}/{$this->comment}"; + } }