contacts_events-8.x-1.x-dev/src/BookingSupervisionHelper.php
src/BookingSupervisionHelper.php
<?php
namespace Drupal\contacts_events;
use Drupal\Component\Datetime\DateTimePlus;
use Drupal\contacts_events\Entity\TicketInterface;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
/**
* Helper for working with child supervision for a booking.
*/
class BookingSupervisionHelper implements BookingSupervisionHelperInterface {
/**
* The order items field items we are working with.
*
* @var \Drupal\Core\Field\EntityReferenceFieldItemList
*/
protected $orderItems;
/**
* The number of child/adult delegates.
*
* Keys are:
* - adult: The delegates over 18 count.
* - non_adult: The delegates not over 18 count.
*
* @var array
*/
protected $delegates;
/**
* Construct the booking supervision helper.
*
* @param \Drupal\Core\Field\EntityReferenceFieldItemListInterface $items
* The order items field of an order.
*/
public function __construct(EntityReferenceFieldItemListInterface $items) {
$this->orderItems = $items;
}
/**
* {@inheritdoc}
*/
public function getAdultDelegates() : int {
$this->calculateDelegates();
return $this->delegates['adult'];
}
/**
* {@inheritdoc}
*/
public function getNonAdultDelegates() : int {
$this->calculateDelegates();
return $this->delegates['non_adult'];
}
/**
* Calculate the delegate counts for the order.
*/
protected function calculateDelegates() : void {
if (isset($this->delegates)) {
return;
}
$this->delegates = [
'adult' => 0,
'non_adult' => 0,
];
/** @var \Drupal\commerce_order\Entity\OrderItemInterface $order_item */
foreach ($this->orderItems->referencedEntities() as $order_item) {
if ($order_item->bundle() != 'contacts_ticket') {
continue;
}
/** @var \Drupal\contacts_events\Entity\TicketInterface $ticket */
$ticket = $order_item->getPurchasedEntity();
if ($ticket->getStatus() == 'cancelled') {
continue;
}
// Count number of adult and non adult tickets.
if ($this->isDelegateAdult($ticket)) {
$this->delegates['adult']++;
}
else {
$this->delegates['non_adult']++;
}
}
}
/**
* Check the age of the delegate at the event is over 18.
*
* @param \Drupal\contacts_events\Entity\TicketInterface $ticket
* Ticket to get the date of birth from.
*
* @return bool
* Whether the delegate will be an adult.
*/
protected function isDelegateAdult(TicketInterface $ticket) : bool {
/** @var \Drupal\Component\Datetime\DateTimePlus|null $date_of_birth */
$date_of_birth = $ticket->hasField('date_of_birth') ? $ticket->get('date_of_birth')->date : NULL;
if (!$date_of_birth) {
return TRUE;
}
/** @var \Drupal\Component\Datetime\DateTimePlus $event_date */
$event_date = $ticket->getEvent()->get('date')->start_date ?: new DateTimePlus();
// Set both times to midnight.
$date_of_birth->setTime(0, 0, 0);
$event_date->setTime(0, 0, 0);
$diff = $date_of_birth->diff($event_date);
return $diff->y >= 18;
}
}
