Skip to content

Instantly share code, notes, and snippets.

@gersonfs
Created March 24, 2022 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gersonfs/99e9821c1c5fb828f044d4a5a04b0844 to your computer and use it in GitHub Desktop.
Save gersonfs/99e9821c1c5fb828f044d4a5a04b0844 to your computer and use it in GitHub Desktop.
DTO PeriodoMensal
<?php
namespace App\Dominio\ObjetoValor;
class PeriodoMensal
{
private int $mes;
private int $ano;
private string $separador;
public function __construct(int $mes, int $ano, string $separador = '/')
{
if ($mes < 1 || $mes > 12) {
throw new \InvalidArgumentException('Mês ' . $mes . ' é inválido!');
}
if (strlen((string)$ano) != 4) {
throw new \InvalidArgumentException("Ano {$ano} é inválido!");
}
$this->mes = $mes;
$this->ano = $ano;
$this->separador = $separador;
}
public static function buildFromDate(\DateTimeInterface $data): self
{
return new self((int)$data->format('m'), (int)$data->format('Y'));
}
public static function current(): self
{
return new self((int)date('m'), (int)date('Y'));
}
/**
* @param string $periodo Informar no formato mes/ano
*/
public static function fromString(string $periodo): self
{
$separador = null;
if (strpos($periodo, '/') !== false) {
$separador = '/';
}
if (strpos($periodo, '-') !== false) {
$separador = '-';
}
if (!preg_match('/[0-9]{1,2}\\' . $separador . '[0-9]{4}/', $periodo)) {
throw new \InvalidArgumentException("O período {$periodo} não está num formato válido!");
}
$p = explode($separador, $periodo);
return new self((int)$p[0], (int)$p[1], $separador);
}
public function __toString(): string
{
return sprintf('%02d' . $this->separador . '%d', $this->mes, $this->ano);
}
public function primeiroDiaMes(): \DateTimeImmutable
{
return new \DateTimeImmutable("{$this->ano}-{$this->mes}-01 00:00:00");
}
public function primeiroDiaMesString(): string
{
return $this->primeiroDiaMes()->format('Y-m-d');
}
public function ultimoDiaMes(): \DateTimeImmutable
{
$primeiroDia = $this->primeiroDiaMes();
$ultimoDia = $primeiroDia->format('t');
return new \DateTimeImmutable("{$this->ano}-{$this->mes}-$ultimoDia 23:59:59");
}
public function ultimoDiaMesString(): string
{
return $this->ultimoDiaMes()->format('Y-m-d');
}
public function getMes(): int
{
return $this->mes;
}
public function getAno(): int
{
return $this->ano;
}
public function incrementarMes(): self
{
$mes = $this->mes;
$ano = $this->ano;
$mes++;
if ($mes > 12) {
$mes = 1;
$ano++;
}
return new self($mes, $ano, $this->separador);
}
public function toInt(): int
{
return (int)($this->ano . sprintf('%02d', $this->mes));
}
public function menorOuIgualA(PeriodoMensal $periodo): bool
{
return $this->toInt() <= $periodo->toInt();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment