Variations.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 \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);
  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. /**
  50. * Filter on types, example usage
  51. * ```
  52. * $variations->filter(function ($entity) {
  53. * return $entity instanceof Temperature;
  54. * );
  55. * ```
  56. *
  57. * @return \Generator
  58. */
  59. public function filter(callable $filterFn): \Generator {
  60. foreach ($this as $data)
  61. if (($match = $data->filter($filterFn)) != null)
  62. yield $match;
  63. return null;
  64. }
  65. /**
  66. * {@inheritDoc}
  67. */
  68. public function getIterator(): \Generator {
  69. foreach ($this->data as $data)
  70. yield $data;
  71. }
  72. }