|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace MLL\Utils\IlluminaSampleSheet\V2\BclConvert; |
| 4 | + |
| 5 | +use MLL\Utils\IlluminaSampleSheet\Section; |
| 6 | + |
| 7 | +class DataSection implements Section |
| 8 | +{ |
| 9 | + /** @var array<BclSample> */ |
| 10 | + protected array $dataRows = []; |
| 11 | + |
| 12 | + public function addSample(BclSample $bclSample): void |
| 13 | + { |
| 14 | + $this->dataRows[] = $bclSample; |
| 15 | + } |
| 16 | + |
| 17 | + public function convertSectionToString(): string |
| 18 | + { |
| 19 | + /** @var array<string> $samplePropertiesOfFirstSample */ |
| 20 | + $samplePropertiesOfFirstSample = array_keys(get_object_vars($this->dataRows[0])); |
| 21 | + foreach ($this->dataRows as $sample) { |
| 22 | + $actualProperties = array_keys(get_object_vars($sample)); |
| 23 | + if ($samplePropertiesOfFirstSample !== $actualProperties) { |
| 24 | + throw new \Exception('All samples must have the same properties. Expected: ' . \Safe\json_encode($samplePropertiesOfFirstSample) . ', Actual: ' . \Safe\json_encode($actualProperties)); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + $bclConvertDataHeaderLines = $this->generateDataHeaderByProperties($samplePropertiesOfFirstSample); |
| 29 | + |
| 30 | + $bclConvertDataLines = [ |
| 31 | + '[BCLConvert_Data]', |
| 32 | + $bclConvertDataHeaderLines, |
| 33 | + ]; |
| 34 | + |
| 35 | + foreach ($this->dataRows as $dataRow) { |
| 36 | + $bclConvertDataLines[] = implode(',', $dataRow->toArray()); |
| 37 | + } |
| 38 | + |
| 39 | + return implode("\n", $bclConvertDataLines) . "\n"; |
| 40 | + } |
| 41 | + |
| 42 | + /** @param array<string> $samplePropertiesOfFirstSample */ |
| 43 | + protected function generateDataHeaderByProperties(array $samplePropertiesOfFirstSample): string |
| 44 | + { |
| 45 | + $samplePropertiesOfFirstSample = array_filter($samplePropertiesOfFirstSample, fn (string $value) // @phpstan-ignore-next-line Variable property access on a non-object required here |
| 46 | + => $this->dataRows[0]->$value !== null); |
| 47 | + |
| 48 | + $samplePropertiesOfFirstSample = array_map(fn (string $value) => ucfirst($value), $samplePropertiesOfFirstSample); |
| 49 | + |
| 50 | + return implode(',', $samplePropertiesOfFirstSample); |
| 51 | + } |
| 52 | +} |
0 commit comments