Variation.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Yr\Forecast\Tabular\Variation;
  3. use App\Yr\Forecast\Tabular\Time;
  4. use App\Yr\Forecast\Tabular\Time\DiffInterface;
  5. if (!function_exists('array_key_last')) {
  6. function array_key_last(array $args): ?int {
  7. $keys = array_keys($args);
  8. return array_pop($keys);
  9. }
  10. }
  11. class Variation implements \IteratorAggregate {
  12. private $time;
  13. private $entities = [];
  14. private $intersects = [];
  15. public function __construct(Time $t) {
  16. $this->time = $t;
  17. }
  18. public function addEntity(DiffInterface $entity, ?DiffInterface $intersects): self {
  19. $this->entities[] = $entity;
  20. if ($intersects != null)
  21. $this->intersects[array_key_last($this->entities)] = $intersects;
  22. return $this;
  23. }
  24. public function getTime(): Time {
  25. return $this->time;
  26. }
  27. public function getIntersection(DiffInterface $entity): ?DiffInterface {
  28. $key = (function() use ($entity) : int {
  29. foreach ($this->entities as $key => $ent)
  30. if ($ent == $entity)
  31. return $key;
  32. })();
  33. if (isset($this->intersects[$key]))
  34. return $this->intersects[$key];
  35. return null;
  36. }
  37. public function isEmpty(): bool {
  38. return empty($this->entities);
  39. }
  40. public function getIterator(): \Generator {
  41. foreach ($this->entities as $entity)
  42. yield $entity;
  43. }
  44. }