123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- <?php
- namespace App\Yr\Forecast\Tabular;
- use App\Yr\Forecast\Tabular\Time\DiffInterface;
- use App\Yr\Forecast\Tabular\Variation\Variation;
- /**
- * Removes superfluous forecast data in an Time-object
- * only storing changes.
- *
- * @author Joachim M. Giæver (joachim[]giaever.org)
- */
- class Variations implements TimeInterface, \IteratorAggregate {
- private $time;
- private $data = [];
- /**
- * @param array $t Array of Time-objects
- */
- public function __construct(array $t) {
- $time = array_shift($t);
- if (!$time instanceof Time)
- return;
- $this->time = $time;
- $var = new Variation($time);
- foreach($time as $entity)
- $var->addEntity($entity, null);
- $this->data[] = $var;
- foreach ($t as $time) {
- $var = new Variation($time instanceof Variation ? $time->getTime() : $time);
- foreach($time as $entity)
- $this->match($var, $entity);
- if (!$var->isEmpty())
- $this->data[] = $var;
- }
- array_shift($this->data);
- }
- private function match(Variation $var, DiffInterface $entity): void {
- foreach(array_reverse($this->data) as $data) {
- foreach ($data as $dentity) {
- if ($entity instanceof $dentity) {
- if ($entity->diff($dentity))
- $var->addEntity($entity, $data == null ? "NULL" : $data);
- return;
- }
- }
- }
- }
- public function getTime(): Time {
- return $this->time;
- }
- public function getFrom(): \DateTimeImmutable {
- return $this->time->getFrom();
- }
- public function getUntil(): \DateTimeImmutable {
- $last = array_shift(array_reverse($this->data));
- if ($last)
- return $last->getUntil();
- return $this->time->getUntil();
- }
- /**
- * Filter on types, example usage
- * ```
- * $variations->filter(function ($entity) {
- * return $entity instanceof Temperature;
- * );
- * ```
- *
- * @return \Generator
- */
- public function filter(callable $filterFn): Variations {
- $time = [$this->getTime()];
- foreach ($this as $data)
- if (($match = $data->filter($filterFn)) != null)
- $time[] = $match;
- return new Variations($time);
- }
- /**
- * {@inheritDoc}
- */
- public function getIterator(): \Generator {
- foreach ($this->data as $data)
- yield $data;
- }
- }
|