Variations.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace App\Yr\Forecast\Tabular;
  3. use App\Yr\Forecast\Tabular\Time\DiffInterface;
  4. use App\Yr\Forecast\Tabular\Variation\Variation;
  5. /**
  6. * Removes superfluous forecast data in an Time-object
  7. * only storing changes.
  8. *
  9. * @author Joachim M. Giæver (joachim[]giaever.org)
  10. */
  11. class Variations implements TimeInterface, \IteratorAggregate {
  12. private $time;
  13. private $data = [];
  14. /**
  15. * @param array $t Array of Time-objects
  16. */
  17. public function __construct(array $t) {
  18. $time = array_shift($t);
  19. if (!$time instanceof Time)
  20. return;
  21. $this->time = $time;
  22. $var = new Variation($time);
  23. foreach($time as $entity)
  24. $var->addEntity($entity, null);
  25. $this->data[] = $var;
  26. foreach ($t as $time) {
  27. $var = new Variation($time instanceof Variation ? $time->getTime() : $time);
  28. foreach($time as $entity)
  29. $this->match($var, $entity);
  30. if (!$var->isEmpty())
  31. $this->data[] = $var;
  32. }
  33. array_shift($this->data);
  34. }
  35. private function match(Variation $var, DiffInterface $entity): void {
  36. foreach(array_reverse($this->data) as $data) {
  37. foreach ($data as $dentity) {
  38. if ($entity instanceof $dentity) {
  39. if ($entity->diff($dentity))
  40. $var->addEntity($entity, $data == null ? "NULL" : $data);
  41. return;
  42. }
  43. }
  44. }
  45. }
  46. public function getTime(): Time {
  47. return $this->time;
  48. }
  49. public function getFrom(): \DateTimeImmutable {
  50. return $this->time->getFrom();
  51. }
  52. public function getUntil(): \DateTimeImmutable {
  53. $last = array_shift(array_reverse($this->data));
  54. if ($last)
  55. return $last->getUntil();
  56. return $this->time->getUntil();
  57. }
  58. /**
  59. * Filter on types, example usage
  60. * ```
  61. * $variations->filter(function ($entity) {
  62. * return $entity instanceof Temperature;
  63. * );
  64. * ```
  65. *
  66. * @return \Generator
  67. */
  68. public function filter(callable $filterFn): Variations {
  69. $time = [$this->getTime()];
  70. foreach ($this as $data)
  71. if (($match = $data->filter($filterFn)) != null)
  72. $time[] = $match;
  73. return new Variations($time);
  74. }
  75. /**
  76. * {@inheritDoc}
  77. */
  78. public function getIterator(): \Generator {
  79. foreach ($this->data as $data)
  80. yield $data;
  81. }
  82. }