Tabular.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. * to only show from sunset today unti sunrise tomorrow
  68. *
  69. * @return Tabular with new collection
  70. */
  71. public function getBetween(\DateTimeInterface $from, \DateTimeInterface $until): self {
  72. $n = new Tabular(null);
  73. foreach ($this as $time)
  74. if ($time->getFrom() >= $from && $time->getUntil() <= $until)
  75. $n->addTime($time);
  76. return $n;
  77. }
  78. /**
  79. * {@inheritDoc}
  80. */
  81. public function getIterator(): \Generator {
  82. foreach ($this->time as $time)
  83. yield $time;
  84. }
  85. }