File size: 2,464 Bytes
cf14c12 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | <?php
declare(strict_types=1);
namespace Billing\Application\CommandHandlers;
use Billing\Application\Commands\CreateOrderCommand;
use Billing\Domain\Entities\OrderEntity;
use Billing\Domain\Events\OrderCreatedEvent;
use Billing\Domain\Exceptions\PlanNotFoundException;
use Billing\Domain\Repositories\OrderRepositoryInterface;
use Billing\Domain\Repositories\PlanRepositoryInterface;
use Billing\Domain\ValueObjects\TrialPeriodDays;
use Easy\Container\Attributes\Inject;
use Psr\EventDispatcher\EventDispatcherInterface;
use Shared\Domain\ValueObjects\CurrencyCode;
use Shared\Domain\ValueObjects\Id;
use Workspace\Domain\Exceptions\WorkspaceNotFoundException;
use Workspace\Infrastructure\Repositories\DoctrineOrm\WorkspaceRepository;
class CreateOrderCommandHandler
{
public function __construct(
private OrderRepositoryInterface $orepo,
private WorkspaceRepository $wrepo,
private PlanRepositoryInterface $prepo,
private EventDispatcherInterface $dispatcher,
#[Inject('option.billing.trial_period_days')]
private ?int $trialPeriodDays = null,
#[Inject('option.billing.trial_without_payment')]
private ?bool $trialWithoutPayment = null,
#[Inject('option.billing.currency')]
private ?string $currency = null,
) {
}
/**
* @param CreateOrderCommand $cmd
* @return OrderEntity
* @throws WorkspaceNotFoundException
* @throws PlanNotFoundException
*/
public function handle(CreateOrderCommand $cmd): OrderEntity
{
$ws = $cmd->workspace instanceof Id
? $this->wrepo->ofId($cmd->workspace) : $cmd->workspace;
$plan = $cmd->plan instanceof Id
? $this->prepo->ofId($cmd->plan) : $cmd->plan;
$order = new OrderEntity(
$ws,
$plan,
CurrencyCode::tryFrom($this->currency) ?? CurrencyCode::USD,
new TrialPeriodDays($this->trialPeriodDays)
);
if (
$this->trialWithoutPayment
&& $order->getTrialPeriodDays()->value > 0
) {
// Mark the order as paid
$order->pay();
}
if ($order->getTotalPrice()->value === 0) {
$order->pay();
}
$this->orepo->add($order);
// Dispatch the order created event
$event = new OrderCreatedEvent($order);
$this->dispatcher->dispatch($event);
return $order;
}
}
|