ActiveHours.php in SMS Framework 2.1.x
File
modules/sms_user/src/ActiveHours.php
View source
<?php
declare (strict_types=1);
namespace Drupal\sms_user;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\sms\Entity\SmsMessageInterface;
use Drupal\user\UserInterface;
use Drupal\Core\Datetime\DrupalDateTime;
class ActiveHours implements ActiveHoursInterface {
protected $configFactory;
protected $status = NULL;
protected $ranges = [];
public function __construct(ConfigFactoryInterface $config_factory) {
$this->configFactory = $config_factory;
}
public function inHours(UserInterface $user, $now = 'now') {
$this
->build();
if (!$this->status) {
return TRUE;
}
$timezone = $user
->getTimeZone();
$now = new DrupalDateTime($now, $timezone);
foreach ($this
->getRanges($timezone) as $date) {
if ($now >= $date
->getStartDate() && $now <= $date
->getEndDate()) {
return TRUE;
}
}
return FALSE;
}
public function findNextTime(UserInterface $user, $now = 'now') {
$timezone = $user
->getTimeZone();
$now = new DrupalDateTime($now, $timezone);
foreach ($this
->getRanges($timezone) as $date) {
if ($now > $date
->getEndDate()) {
continue;
}
return $date;
}
return FALSE;
}
public function delaySmsMessage(SmsMessageInterface &$sms_message) {
$recipient = $sms_message
->getRecipientEntity();
if ($sms_message
->isAutomated() && $recipient instanceof UserInterface) {
if (!$this
->inHours($recipient) && ($range = $this
->findNextTime($recipient))) {
$sms_message
->setSendTime($range
->getStartDate()
->format('U'));
}
}
}
public function getRanges($timezone) {
$this
->build();
$dates = [];
foreach ($this->ranges as $range) {
$dates[] = new ActiveHoursDates(new DrupalDateTime($range['start'], $timezone), new DrupalDateTime($range['end'], $timezone));
}
usort($dates, function ($a, $b) {
if ($a
->getStartDate() == $b
->getStartDate()) {
return 0;
}
return $a
->getStartDate() < $b
->getStartDate() ? -1 : 1;
});
return $dates;
}
protected function build() {
if (isset($this->status)) {
return;
}
$settings = $this->configFactory
->get('sms_user.settings')
->get('active_hours');
$this->status = !empty($settings['status']);
$this->ranges = !empty($settings['ranges']) ? $settings['ranges'] : [];
}
}