Tabular.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace App\Yr\Forecast;
  3. use App\Yr\Forecast\Tabular\Statistics;
  4. use App\Yr\Forecast\Tabular\Time;
  5. use App\Yr\Forecast\Tabular\Variations;
  6. /**
  7. * Holds the forecast data in Time-objects.
  8. *
  9. * Use the ```getBetween``` option to limit the results.
  10. *
  11. * Class also makes a simple statistic on the forecast
  12. * for the periode and a variation that will exclude
  13. * repetitive forecast data.
  14. *
  15. * @author Joachim M. Giæver (joachim[]giaver.org)
  16. */
  17. class Tabular implements \IteratorAggregate {
  18. private $time = [];
  19. private $stats;
  20. /**
  21. * @param \SimpleXMLElement $xml The xml part holding the time objects, can be null
  22. */
  23. public function __construct(?\SimpleXMLElement $xml) {
  24. $this->stats = new Statistics();
  25. if ($xml != null)
  26. foreach ($xml->time as $time)
  27. $this->addTime(new Time($time));
  28. }
  29. /**
  30. * Add a Time-object to the tabular
  31. *
  32. * @return Tabular
  33. */
  34. protected function addTime(Time $time): self {
  35. $this->time[] = $time;
  36. $this->stats->analyse($time);
  37. return $this;
  38. }
  39. /**
  40. * Get statistics for the Time-object collection
  41. *
  42. * @return Statistics
  43. */
  44. public function getStatistics(): Statistics {
  45. return $this->stats;
  46. }
  47. /**
  48. * Remove superfluous weather data.
  49. *
  50. * Checks if the data in the Time-object differs from
  51. * the current Time-object and returns the unique data
  52. *
  53. * @return Variations
  54. */
  55. public function getVariations(): Variations {
  56. return new Variations($this->time);
  57. }
  58. /**
  59. * Filter data between a certain periode, e.g
  60. * ```
  61. * $forcast->between(
  62. * $forcast->getSunset(),
  63. * $forecast->getSunrise()->add(
  64. * new \DateInterval('P1D')
  65. * )
  66. * );
  67. * ```
  68. * to only show from sunset today unti sunrise tomorrow
  69. *
  70. * @return Tabular with new collection
  71. */
  72. public function getBetween(\DateTimeInterface $from, \DateTimeInterface $until): self {
  73. $n = new Tabular(null);
  74. foreach ($this as $time)
  75. if ($time->getFrom() >= $from && $time->getUntil() <= $until)
  76. $n->addTime($time);
  77. return $n;
  78. }
  79. public function getFrom(): \DateTimeInterface {
  80. return current($this->time)->getFrom();
  81. }
  82. public function getUntil(): \DateTimeInterface {
  83. return current(array_reverse($this->time))->getUntil();
  84. }
  85. /**
  86. * {@inheritDoc}
  87. */
  88. public function getIterator(): \Generator {
  89. foreach ($this->time as $time)
  90. yield $time;
  91. }
  92. }