Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
class BusinessDayPeriodIterator implements \Iterator
{
private $current;
private $period = [];
public function __construct(\DatePeriod $period) {
$this->period = $period;
$this->current = $this->period->getStartDate();
if(!$period->include_start_date){
$this->next();
}
$this->endDate = $this->period->getEndDate();
}
public function rewind() {
$this->current->subtract($this->period->getDateInterval());
}
public function current() {
return clone $this->current;
}
public function key() {
return $this->current->diff($this->period->getStartDate());
}
public function next() {
$this->current->add($this->period->getDateInterval());
}
public function valid() {
return $this->current < $this->endDate;
}
public function extend()
{
$this->endDate->add($this->period->getDateInterval());
}
public function isSaturday()
{
return $this->current->format('N') == 6;
}
public function isSunday()
{
return $this->current->format('N') == 7;
}
public function isWeekend()
{
return ($this->isSunday() || $this->isSaturday());
}
}
@rafaelfelipesantos

This comment has been minimized.

Copy link

@rafaelfelipesantos rafaelfelipesantos commented Oct 8, 2020

Bro, why not a FilterIterator?

@styks1987

This comment has been minimized.

Copy link
Owner Author

@styks1987 styks1987 commented Oct 8, 2020

@manofirmz that is a great idea! I think when I wrote this I was just starting with iterators. BTW, how did you come across this gist?

@rafaelfelipesantos

This comment has been minimized.

Copy link

@rafaelfelipesantos rafaelfelipesantos commented Oct 9, 2020

@manofirmz que ótima ideia! Acho que quando escrevi isso, estava apenas começando com os iteradores. BTW, como você descobriu essa essência?

When I think of iterators, I think of collections. In this case, a collection of Dates, or Periods / Intervals. Therefore, a filter for working days makes perfect sense, based on a collection.

@rafaelfelipesantos

This comment has been minimized.

Copy link

@rafaelfelipesantos rafaelfelipesantos commented Oct 9, 2020

@manofirmz that is a great idea! I think when I wrote this I was just starting with iterators. BTW, how did you come across this gist?

Here: https://www.php.net/manual/en/class.dateperiod.php

:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.