|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Infrastructure\Reader; |
| 4 | + |
| 5 | +use App\Application\Cache\DatasetCacheInterface; |
| 6 | +use App\Application\Path\AppPathResolver; |
| 7 | +use App\Domain\PowerStation; |
| 8 | +use Doctrine\Common\Collections\ArrayCollection; |
| 9 | +use League\Csv\Reader; |
| 10 | +use Symfony\Component\Validator\Validator\ValidatorInterface; |
| 11 | + |
| 12 | +readonly class PowerStationDatasetReader |
| 13 | +{ |
| 14 | + public function __construct( |
| 15 | + private AppPathResolver $appPathResolver, |
| 16 | + private DatasetCacheInterface $datasetCache, |
| 17 | + private ValidatorInterface $validator, |
| 18 | + ) { |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * @return ArrayCollection<string, ArrayCollection<int, PowerStation>> |
| 23 | + */ |
| 24 | + public function read(): ArrayCollection |
| 25 | + { |
| 26 | + return $this->datasetCache->get( |
| 27 | + sprintf('%s_dataset', self::class), |
| 28 | + function () { |
| 29 | + $dataset = new ArrayCollection(); |
| 30 | + $valid = new ArrayCollection(); |
| 31 | + $invalid = new ArrayCollection(); |
| 32 | + $dataset->set('valid', $valid); |
| 33 | + $dataset->set('invalid', $invalid); |
| 34 | + |
| 35 | + $data = Reader::createFromPath($this->appPathResolver->getResourcesPath('elektrownia.csv')); |
| 36 | + $data->setHeaderOffset(0); |
| 37 | + |
| 38 | + foreach ($data as $row) { |
| 39 | + $powerStation = $this->createPowerStation($row); |
| 40 | + $errors = $this->validator->validate($powerStation); |
| 41 | + |
| 42 | + if ($errors->count() === 0) { |
| 43 | + $valid->add($powerStation); |
| 44 | + } else { |
| 45 | + $invalid->add($powerStation); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return $dataset; |
| 50 | + } |
| 51 | + ); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * @param array<string, string> $data |
| 56 | + */ |
| 57 | + private function createPowerStation(array $data): PowerStation |
| 58 | + { |
| 59 | + return new PowerStation( |
| 60 | + temperature: round((float) ($data['Temperatura'] ?? 0.0), 2), |
| 61 | + fumes: round((float) ($data['Spaliny'] ?? 0.0), 2), |
| 62 | + pressure: round((float) ($data['Ciśnienie'] ?? 0.0), 2), |
| 63 | + humidity: round((float) ($data['Wilgotność'] ?? 0.0), 2), |
| 64 | + power: round((float) ($data['Moc'] ?? 0.0), 2), |
| 65 | + ); |
| 66 | + } |
| 67 | +} |
0 commit comments