| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\EventTickets\Actions; |
| 4 |
|
| 5 |
use Give\Donations\Models\Donation; |
| 6 |
use Give\EventTickets\DataTransferObjects\TicketPurchaseData; |
| 7 |
use Give\EventTickets\Models\EventTicket; |
| 8 |
use Give\Framework\Exceptions\Primitives\RuntimeException; |
| 9 |
use Give\Framework\Support\ValueObjects\Money; |
| 10 |
|
| 11 |
/** |
| 12 |
* @since 3.6.0 |
| 13 |
*/ |
| 14 |
class GenerateTicketsFromPurchaseData |
| 15 |
{ |
| 16 |
/** |
| 17 |
* @since 3.6.0 |
| 18 |
* @var Donation |
| 19 |
*/ |
| 20 |
protected $donation; |
| 21 |
|
| 22 |
/** |
| 23 |
* @since 3.6.0 |
| 24 |
*/ |
| 25 |
public function __construct(Donation $donation) |
| 26 |
{ |
| 27 |
$this->donation = $donation; |
| 28 |
} |
| 29 |
|
| 30 |
/** |
| 31 |
* @since 4.16.8.1 Stop relying on a count taken once before the loop — EventTicketRepository::insert() now enforces remaining capacity itself, atomically with each insert, closing a race that let concurrent purchases jointly oversell a ticket type. |
| 32 |
* @since 4.6.0 Add support for currency conversion |
| 33 |
* @since 3.20.0 Add "amount" to the array of props |
| 34 |
* @since 3.6.0 |
| 35 |
*/ |
| 36 |
public function __invoke(TicketPurchaseData $data) |
| 37 |
{ |
| 38 |
$quantity = max(0, $data->quantity); |
| 39 |
|
| 40 |
for($i = 0; $i < $quantity; $i++) { |
| 41 |
$amount = $data->ticketType->price; |
| 42 |
|
| 43 |
if ($this->donation->amount->getCurrency() !== $data->ticketType->price->getCurrency()) { |
| 44 |
$amount = new Money($data->ticketType->price->multiply($this->donation->exchangeRate)->getAmount(), $this->donation->amount->getCurrency()); |
| 45 |
} |
| 46 |
|
| 47 |
try { |
| 48 |
EventTicket::create([ |
| 49 |
'eventId' => $data->ticketType->eventId, |
| 50 |
'ticketTypeId' => $data->ticketType->id, |
| 51 |
'donationId' => $this->donation->id, |
| 52 |
'amount' => $amount, |
| 53 |
]); |
| 54 |
} catch (RuntimeException $exception) { |
| 55 |
break; |
| 56 |
} |
| 57 |
} |
| 58 |
} |
| 59 |
} |
| 60 |
|